﻿Option Strict Off
Option Explicit On
Imports System.Data.SqlClient
Imports System.Data.Odbc
Imports Suprema
Imports System.Text
Imports System.IO
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Printing


Public Class frmLiquidacion
    Inherits System.Windows.Forms.Form
    Dim handle_Renamed As Integer
    Dim deviceType As Integer
    Dim userID As Integer
    Dim result As Integer

    Private admComercial As New AdminPAQ_Comercial

    Dim Bitacora As New clsActividad
    Dim Usuario As New clsUsuarioPrincipal
    Private mstrCondicion As String
    Dim liq As New clsLiquidacion
    Dim Es_Buscado As Boolean
    Dim OrigenNombre As String
    Private prtSettingsBoletos As PrinterSettings
    Private prtDoc1Boletos As PrintDocument
    Private prtDoc2Boletos As PrintDocument
    Private prtDoc3Boletos As PrintDocument
    Private prtFontBoletos As System.Drawing.Font
    Private lineaActualBoletos As Integer
    Private prtSettingsCuota As PrinterSettings
    Private prtDoc1Cuota As PrintDocument
    Private prtDoc2Cuota As PrintDocument
    Private prtDoc3Cuota As PrintDocument
    Private prtFontCuota As System.Drawing.Font
    Private lineaActual As Integer

    Private minuto As Integer = 0
    Private segundo As Integer = 0
    Private milisegundo As Integer = 0

    Dim Continuar As Boolean
    Dim FalloalAbrir As Boolean = False

    Dim ConnectionACG As String
    Dim ConnectionAUSL As String
    Dim ConnectionASP As String
    Dim ConnectionLCB As String
    Dim ConnectionAvailable As String
    Dim Registros As Integer
    Dim Actual As Integer
    Dim Operador As New clsOperadoresGlobal
    Public WriteOnly Property Condicion() As String
        Set(ByVal value As String)
            mstrCondicion = value
        End Set
    End Property
    Private Sub frmLiquidacion_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If FalloalAbrir = True Then
            BS_CloseSocket(handle_Renamed)
        Else
            BS_CloseSocket(handle_Renamed)
        End If


        Bitacora.RegistraActividad("Cerró al Módulo de Liquidación")
        Usuario.Ubicacion("Ventana Principal")
    End Sub
    Private Sub frmLiquidacion_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ToolStrip1.Cursor = Cursors.Hand
        ToolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System

        chScanner.Checked = True
        chScanner.Checked = False

        radioLiquidacion.Checked = True
        datFecha.Value = Now()
        CargaLiquidadores()
        CargaOperadoresGlobal()
        CargaBuses()
        CargaRutas()
        CargaUbicaciones()

        OrigenNombre = ""
        lblStatusDia.Text = ""
        lblStatusImportacion.Text = ""
        lblStatusLiquidacion.Text = ""

        TabPage1.Parent = TabControl1
        TabControl1.SelectedTab = TabPage1
        TabPage2.Parent = Nothing
        TabPage4.Parent = Nothing

        txtFolio.Text = -1
        txtFolio.Text = 0
        Es_Buscado = False

        chImprimir.Checked = True

        TotalLiquidacion()

        Bitacora.RegistraActividad("Ingresó al Módulo de Liquidación")
        Usuario.Ubicacion("Módulo de Liquidación")

        txtSerie.SelectAll()
        txtSerie.Focus()
        Application.DoEvents()
    End Sub
    Sub IniciaLector()
        result = BS_InitSDK()
        userID = 0

        Dim deviceID As Object
        Dim IP As String = txtIPScanner.Text
        result = BS_OpenSocket(IP, 1471, handle_Renamed)
        If result <> 0 Then
            txtConexion.AppendText("No se pudo abrir el canal de comunicación " & IP & vbNewLine)
            FalloalAbrir = True
            Exit Sub
        End If

        result = BS_GetDeviceID(handle_Renamed, deviceID, deviceType)
        If result <> 0 Then
            txtConexion.AppendText("No se pudo obtener el ID del dispositivo" & vbNewLine)
            FalloalAbrir = True
            Exit Sub
        End If

        result = BS_SetDeviceID(handle_Renamed, deviceID, deviceType)

        If result <> 0 Then
            txtConexion.AppendText("No se pudo asignar el ID del dispositivo" & vbNewLine)
            FalloalAbrir = True
            Exit Sub
        End If

        FalloalAbrir = False
        txtConexion.AppendText("Se abrio correctamente el canal de comunicación" & vbNewLine)
    End Sub
    Sub BuscaPagobus()
        Dim FechaLiquidacion As String = datFecha.Value.ToString("MM/dd/yyyy")
        Dim IdOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM OperadoresGlobal WHERE UPPER(Nombre)='" & UCase(txtOperador.Text) & "'")
        txtGeneral.Text = BuscarDblDatoCitra("SELECT SUM(General) as General from PagobusDetallado WHERE CONVERT(VARCHAR,Fecha,101)='" & FechaLiquidacion & "' AND IdAutobus=" & txtCidClien01.Text & " AND IdOperador=" & IdOperador)
        txtPreferencial.Text = BuscarDblDatoCitra("SELECT SUM(Preferencial) as Preferencial from PagobusDetallado WHERE CONVERT(VARCHAR,Fecha,101)='" & FechaLiquidacion & "' AND IdAutobus=" & txtCidClien01.Text & " AND IdOperador=" & IdOperador)

        If txtTotalBoletos.Text > 0 Then
            Dim TotalPagobus As Integer = CInt(txtGeneral.Text) + CInt(txtPreferencial.Text)
            Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - TotalPagobus
            txtTotal.Text = Format(CDbl(TotalBoletos) * 8, "###,###.#0")
        End If


    End Sub
    Sub VerificaTipoLiquidacion()
        If radioPreLiquidacion.Checked = True Then
            txtInicial.Enabled = True
            txtFinal.Enabled = True
            txtPreferencial.Enabled = True
            txtGeneral.Enabled = True
            txtTotal.Enabled = False
        Else
            txtInicial.Enabled = False
            txtFinal.Enabled = False
            txtPreferencial.Enabled = False
            txtGeneral.Enabled = False
            txtTotal.Enabled = True
        End If
    End Sub


    Sub TotalLiquidacion()
        Dim FechaLiquidacion As String = datFecha.Value.ToString("MM/dd/yyyy")
        txtTotalLiquidaciones.Text = BuscarIntDatoCitra("SELECT COUNT(*) FROM Liquidacion WHERE convert(varchar,fecha,101)='" & FechaLiquidacion & "'")
    End Sub
    Sub CargaUbicaciones()
        lstUbicación.Items.Clear()

        Dim cnconn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            cnconn.ConnectionString = InitialConnection
            strSql = "SELECT Descripcion FROM Ubicaciones ORDER BY Descripcion"

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql

            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                lstUbicación.Items.Add(rdBuscar("Descripcion"))
            Loop
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try
    End Sub
    Sub CargaBuses()
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        dgBuses.Rows.Clear()

        Dim strNombre As String
        Dim cnconn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            strNombre = UCase(txtBuscarBus.Text.Trim)
            strNombre = "%" & strNombre.Replace(" ", "%") & "%"

            cnconn.ConnectionString = CitraConnection
            strSql = "Select IdAutobus, cCodigoC01, NoEconomico FROM Autobuses WHERE (Estatus=1 and upper(cCodigoC01) Like '" & strNombre & "' " & mstrCondicion & ") OR  (Estatus=1 and upper(NoEconomico) like '" & strNombre & "' " & mstrCondicion & ")"

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql

            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                dgBuses.Rows.Add(rdBuscar("cCodigoC01").ToString.Trim, rdBuscar("NoEconomico").ToString.Trim, rdBuscar("IdAutobus"))
            Loop
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try

    End Sub
    Sub CargaRutas()
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        dgRuta.Rows.Clear()

        Dim strNombre As String
        Dim cnconn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            strNombre = UCase(txtBuscarRuta.Text.Trim)
            strNombre = "%" & strNombre.Replace(" ", "%") & "%"

            cnconn.ConnectionString = CitraConnection
            strSql = "Select * FROM RUTAS WHERE upper(cCodigoV01) Like '" & strNombre & "' " & mstrCondicion & " OR  upper(Nombre) like '" & strNombre & "' " & mstrCondicion & ""

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql

            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                dgRuta.Rows.Add(rdBuscar("cCodigoV01").ToString.Trim, rdBuscar("Nombre").ToString.Trim)
            Loop
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try

    End Sub
    Private Sub Gatter()
        liq.IdLiquidacion = txtFolio.Text
        liq.Fecha = datFecha.Value
        liq.IdLiquidador = BuscarIntDatoInicial("Liquidadores", "IdEmpleado", "Codigo='" & txtCodigoLiquidador.Text.Trim & "'")
        liq.CodigoLiquidador = txtCodigoLiquidador.Text
        liq.NombreLiquidador = txtAnalista.Text.Trim
        liq.IdOperador = BuscarIntDatoCitra("OperadoresGlobal", "IdEmpleado", "Codigo='" & txtCodigoOperador.Text.Trim & "'")
        liq.CodigoOperaor = txtCodigoOperador.Text
        liq.NombreOperador = txtOperador.Text.Trim
        liq.IdAutobus = txtCidClien01.Text
        liq.NoEconomico = txtAutobus.Text
        liq.IdRuta = BuscarIntDatoCitra("Rutas", "IdRuta", "cCodigoV01='" & txtRuta.Text.Trim & "'")
        liq.NombreRuta = BuscarStrDatoCitra("Rutas", "Nombre", "cCodigoV01='" & txtRuta.Text.Trim & "'")
        If radioPreLiquidacion.Checked = True Then
            liq.TipoLiquidacion = 0
        Else
            liq.TipoLiquidacion = 1
        End If
        liq.Serie = txtSerie.Text.Trim
        liq.NumeracionInicial = txtInicial.Text
        liq.NumeracionFinal = txtFinal.Text
        liq.TotalBoletos = txtTotalBoletos.Text
        liq.Preferencial = txtPreferencial.Text
        liq.General = txtGeneral.Text
        liq.IngresoPreferencial = liq.Preferencial * 3.7
        liq.IngresoGeneral = liq.General * 7.3
        liq.Vueltas = txtVueltas.Text
        liq.Liquidacion = txtTotal.Text
        liq.Importe01 = 0
        liq.Importe02 = 0
        liq.Importe03 = 0
        liq.Importe04 = 0
        liq.Importe05 = 0
        liq.Texto01 = ""
        liq.Texto02 = "0"
        liq.Texto03 = lstUbicación.Text
        liq.Texto04 = ""
        liq.Texto05 = ""
    End Sub

    Private Sub Scatter()
        datFecha.Value = liq.Fecha
        txtCodigoLiquidador.Text = liq.CodigoLiquidador
        txtAnalista.Text = liq.NombreLiquidador
        txtCodigoOperador.Text = liq.CodigoOperaor
        txtOperador.Text = liq.NombreOperador
        txtAutobus.Text = liq.NoEconomico
        txtCidClien01.Text = liq.IdAutobus
        txtRuta.Text = BuscarStrDatoCitra("Rutas", "cCodigoV01", "Nombre='" & liq.NombreRuta & "'")
        If liq.TipoLiquidacion = 0 Then
            radioPreLiquidacion.Checked = True
        Else
            radioLiquidacion.Checked = True
        End If
        txtSerie.Text = liq.Serie
        txtInicial.Text = liq.NumeracionInicial
        txtFinal.Text = liq.NumeracionFinal
        txtTotalBoletos.Text = liq.TotalBoletos
        txtPreferencial.Text = liq.Preferencial
        txtGeneral.Text = liq.General
        txtVueltas.Text = liq.Vueltas
        txtTotal.Text = liq.Liquidacion

        If liq.Texto02 = "0" Or liq.Texto02 = "" Then
            btnNoLiquidado.Enabled = False
            btnLiquidado.Enabled = True
        Else
            btnNoLiquidado.Enabled = False
            btnLiquidado.Enabled = False
        End If

        txtCidBoleto.Text = BuscarIntDatoCitra("Kardex", "IdBoleto", "IdAutobus=" & txtCidClien01.Text & " and Serie='" & txtSerie.Text & "'")

        TotalLiquidacion()

        If liq.Importe03 = 1 Then
            ToolStripButton5.Enabled = False
        Else
            ToolStripButton5.Enabled = True
        End If
    End Sub
    Sub Actualizar()
        Dim intFolio As Integer = 0
        If Me.txtFolio.Text <> "" Then
            intFolio = Me.txtFolio.Text
            liq.IdLiquidacion = Me.txtFolio.Text
        Else
            intFolio = 0
            liq.IdLiquidacion = 0

        End If
        liq.Buscar()
        Scatter()
        Me.txtFolio.Text = intFolio
        liq.IdLiquidacion = Me.txtFolio.Text
    End Sub
    Public Function Num2Text(ByVal value As Double) As String
        Select Case value
            Case 0 : Num2Text = "CERO"
            Case 1 : Num2Text = "UN"
            Case 2 : Num2Text = "DOS"
            Case 3 : Num2Text = "TRES"
            Case 4 : Num2Text = "CUATRO"
            Case 5 : Num2Text = "CINCO"
            Case 6 : Num2Text = "SEIS"
            Case 7 : Num2Text = "SIETE"
            Case 8 : Num2Text = "OCHO"
            Case 9 : Num2Text = "NUEVE"
            Case 10 : Num2Text = "DIEZ"
            Case 11 : Num2Text = "ONCE"
            Case 12 : Num2Text = "DOCE"
            Case 13 : Num2Text = "TRECE"
            Case 14 : Num2Text = "CATORCE"
            Case 15 : Num2Text = "QUINCE"
            Case Is < 20 : Num2Text = "DIECI" & Num2Text(value - 10)
            Case 20 : Num2Text = "VEINTE"
            Case Is < 30 : Num2Text = "VEINTI" & Num2Text(value - 20)
            Case 30 : Num2Text = "TREINTA"
            Case 40 : Num2Text = "CUARENTA"
            Case 50 : Num2Text = "CINCUENTA"
            Case 60 : Num2Text = "SESENTA"
            Case 70 : Num2Text = "SETENTA"
            Case 80 : Num2Text = "OCHENTA"
            Case 90 : Num2Text = "NOVENTA"
            Case Is < 100 : Num2Text = Num2Text(Int(value \ 10) * 10) & " Y " & Num2Text(value Mod 10)
            Case 100 : Num2Text = "CIEN"
            Case Is < 200 : Num2Text = "CIENTO " & Num2Text(value - 100)
            Case 200, 300, 400, 600, 800 : Num2Text = Num2Text(Int(value \ 100)) & "CIENTOS"
            Case 500 : Num2Text = "QUINIENTOS"
            Case 700 : Num2Text = "SETECIENTOS"
            Case 900 : Num2Text = "NOVECIENTOS"
            Case Is < 1000 : Num2Text = Num2Text(Int(value \ 100) * 100) & " " & Num2Text(value Mod 100)
            Case 1000 : Num2Text = "MIL"
            Case Is < 2000 : Num2Text = "MIL " & Num2Text(value Mod 1000)
            Case Is < 1000000 : Num2Text = Num2Text(Int(value \ 1000)) & " MIL"
                If value Mod 1000 Then Num2Text = Num2Text & " " & Num2Text(value Mod 1000)
            Case 1000000 : Num2Text = "UN MILLON"
            Case Is < 2000000 : Num2Text = "UN MILLON " & Num2Text(value Mod 1000000)
            Case Is < 1000000000000.0# : Num2Text = Num2Text(Int(value / 1000000)) & " MILLONES "
                If (value - Int(value / 1000000) * 1000000) Then Num2Text = Num2Text & " " & Num2Text(value - Int(value / 1000000) * 1000000)
            Case 1000000000000.0# : Num2Text = "UN BILLON"
            Case Is < 2000000000000.0# : Num2Text = "UN BILLON " & Num2Text(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
            Case Else : Num2Text = Num2Text(Int(value / 1000000000000.0#)) & " BILLONES"
                If (value - Int(value / 1000000000000.0#) * 1000000000000.0#) Then Num2Text = Num2Text & " " & Num2Text(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
        End Select
    End Function
    Private Sub imprimirPapeletaBoletos(ByVal esPreview As Boolean)

        If prtSettingsBoletos Is Nothing Then
            prtSettingsBoletos = New PrinterSettings
        End If

        If prtDoc3Boletos Is Nothing Then
            prtDoc3Boletos = New System.Drawing.Printing.PrintDocument
            AddHandler prtDoc3Boletos.PrintPage, AddressOf prt_PapeletaBoletosTiket
        End If

        ' la línea actual
        lineaActual = 0

        ' la configuración a usar en la impresión
        prtDoc3Boletos.PrinterSettings = prtSettingsBoletos

        If esPreview Then
            Dim prtPrev As New PrintPreviewDialog
            prtPrev.Document = prtDoc3Boletos

            prtPrev.Text = "Previsualizar documento"
            prtPrev.ShowDialog()
        Else
            prtDoc3Boletos.Print()
        End If
    End Sub
    Private Sub imprimirPapeletaCuota(ByVal esPreview As Boolean)

        If prtSettingsCuota Is Nothing Then
            prtSettingsCuota = New PrinterSettings
        End If

        If prtDoc3Cuota Is Nothing Then
            prtDoc3Cuota = New System.Drawing.Printing.PrintDocument
            AddHandler prtDoc3Cuota.PrintPage, AddressOf prt_PapeletaCuotaTiket
        End If

        ' la línea actual
        lineaActual = 0

        ' la configuración a usar en la impresión
        prtDoc3Cuota.PrinterSettings = prtSettingsCuota

        If esPreview Then
            Dim prtPrev As New PrintPreviewDialog
            prtPrev.Document = prtDoc3Cuota

            prtPrev.Text = "Previsualizar documento"
            prtPrev.ShowDialog()
        Else
            prtDoc3Cuota.Print()
        End If
    End Sub
    Private Sub prt_PapeletaCuota(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        ' Este evento se produce cada vez que se va a imprimir una página
        Dim lineHeight As Single
        Dim yPos As Single = e.MarginBounds.Top
        Dim leftMargin As Single = e.MarginBounds.Left
        Dim printFont As System.Drawing.Font
        Dim sb As System.Text.StringBuilder

        ' Asignar el tipo de letra
        printFont = New System.Drawing.Font("Arial", 12, FontStyle.Bold)
        lineHeight = printFont.GetHeight(e.Graphics)
        '
        'ENCABEZADO
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Coordinado Autobuses Urbanos y Suburbanos de León, S.A. de C.V.")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 140, 12)
        printFont = New System.Drawing.Font("Arial", 11)

        yPos += lineHeight
        sb = New System.Text.StringBuilder
        Dim Empresa As String = BuscarStrDatoCitra("SELECT CVALORCL01 FROM MGW10020 C INNER JOIN MGW10002 A ON C.CIDVALOR01=A.CIDVALOR02 WHERE A.cCODIGOC01='" & txtRuta.Text.Trim & "'")
        sb.AppendFormat("{0} ", "Empresa: " & Empresa)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 238, 42)
        printFont = New System.Drawing.Font("Arial", 10)

        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Papeleta de Liquidación")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 315, 62)

        printFont = New System.Drawing.Font("Arial", 10)

        'Imprime el Operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Operador: " & txtOperador.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 35, 140)


        'Imprime el autobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Autobus: " & txtAutobus.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 35, 175)

        'Imprime la Ruta
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", BuscarStrDatoCitra("Rutas", "Nombre", "cCodigoV01='" & txtRuta.Text.Trim & "'"))
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 35, 210)

        'Imprime la fecha
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Fecha: " & datFecha.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 635, 140)

        'Imprime las vueltas
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Vueltas: " & txtVueltas.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 635, 175)

        'Imprime el tipo
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Tipo: Por Cuota")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 635, 210)

        'Imprime el folio
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", "Folio: " & liq.CidLiquida)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 710, 63)

        'Imprime encabezado boletos
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", "Informacion de Liquidacion")
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 315, 250)

        'Imprime linea 1
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", "_____________________________________________________________________________")
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 259)

        'Imprime encabezado boletos 2
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", "Cuota")
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 122, 273)

        'Imprime linea 2
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", "_____________________________________________________________________________")
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 273)

        'Imprime serie
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", txtSerie.Text.Trim)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 131, 289)

        'Imprime Inicial
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", txtInicial.Text)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 189, 289)

        'Imprime final
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", txtFinal.Text)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 275, 289)

        'Imprime total boletos
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", txtTotalBoletos.Text)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 370, 289)

        'Imprime pagobus
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", txtPagobus.Text)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 471, 289)

        'Imprime pagobus pendiente
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", txtPagobusPendiente.Text)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 612, 289)

        'Imprime linea liquidacion simple
        ' yPos += lineHeight
        ' sb = New System.Text.StringBuilder
        ' sb.AppendFormat("{0} ", "____________________________________________________________")
        ' e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 229, 332)

        Dim total As Double
        Dim decimales As String
        Dim numeros As Integer
        Dim distancia As Integer
        total = txtTotal.Text
        numeros = Len(total)
        If total > 0 And total < 10 Then
            distancia = 3
        ElseIf total > 9 And total < 100 Then
            distancia = 4
        ElseIf total > 99 And total < 1000 Then
            distancia = 5
        ElseIf total > 999 And total < 10000 Then
            distancia = 6
        ElseIf total > 9999 And total < 100000 Then
            distancia = 7
        ElseIf total > 99999 And total > 1000000 Then
            distancia = 8
        ElseIf total > 999999 And total > 10000000 Then
            distancia = 9
        End If
        decimales = Mid((txtTotal.Text), distancia, 2)
        Dim Cantidad As String = Num2Text(Int(total)) & " PESOS " & decimales & "/100 M.N"
        'Imprime total a liquidar
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Total a Liquidar: $" & txtTotal.Text & ".00" & "          (" & Cantidad & ")")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 122, 350)

        'Imprime linea liquidacion doble 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 229, 356)

        'Imprime linea liquidacion doble 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 229, 359)

        'Imprime linea operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 123, 406)

        'Imprime firma operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Conforme Operador")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 140, 420)

        'Imprime linea liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 490, 406)

        'Imprime firma liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtAnalista.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 507, 420)

    End Sub
    Private Sub prt_PapeletaBoletosTiket(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        ' Este evento se produce cada vez que se va a imprimir una página
        Dim lineHeight As Single
        Dim yPos As Single = e.MarginBounds.Top
        Dim leftMargin As Single = e.MarginBounds.Left
        Dim printFont As System.Drawing.Font
        Dim sb As System.Text.StringBuilder

        ' Asignar el tipo de letra
        printFont = New System.Drawing.Font("Arial", 10, FontStyle.Bold)
        lineHeight = printFont.GetHeight(e.Graphics)
        '
        'ENCABEZADO
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Consorcio Optra")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 100, 5)

        printFont = New System.Drawing.Font("Arial", 8)
        yPos += lineHeight
        sb = New System.Text.StringBuilder

        Dim Empresa As String = BuscarStrDatoCitra("SELECT CVALORCL01 FROM MGW10020 C INNER JOIN MGW10002 A ON C.CIDVALOR01=A.CIDVALOR02 WHERE A.cCODIGOC01='" & txtRuta.Text.Trim & "'")
        sb.AppendFormat("{0} ", Empresa)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 20)

        printFont = New System.Drawing.Font("Arial", 8)
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Ticket de Liquidación")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 35)

        printFont = New System.Drawing.Font("Arial", 8)
        'Imprime el Operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Operador: " & txtOperador.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 60)


        'Imprime el autobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Autobus: " & txtAutobus.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 75)

        'Imprime la Ruta
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", BuscarStrDatoCitra("Rutas", "Nombre", "cCodigoV01='" & txtRuta.Text.Trim & "'"))
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 90)

        'Imprime la fecha
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Fecha: " & datFecha.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 105)

        'Imprime las vueltas
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Vueltas: " & txtVueltas.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 120)

        'Imprime el tipo
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Tipo: Por Boletaje")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 135)

        'Imprime el folio
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Folio: " & liq.IdLiquidacion)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 150)

        'Imprime encabezado boletos


        'Imprime linea 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 180)

        'Imprime encabezado boletos 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "            Serie           Del                 Al                 Total")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 190)

        'Imprime linea 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 190)

        'Imprime serie
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtSerie.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 55, 205)

        'Imprime Inicial
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtInicial.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 96, 205)

        'Imprime final
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtFinal.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 160, 205)

        'Imprime total boletos
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtTotalBoletos.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 238, 205)

        
        'Imprime linea 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 220)

        'Imprime encabezado boletos 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "         Pagobus Preferencial      Pagobus General")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 230)

        'Imprime linea 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 230)

        'Imprime pagobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtPreferencial.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 100, 245)

        'Imprime pagobus pendiente
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtGeneral.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 190, 245)

        'Imprime serie

        Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - (CDbl(txtPreferencial.Text) + CDbl(txtGeneral.Text))

        'Imprime boletos realmente vendidos
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Boletos Vendidos: " & TotalBoletos)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 260)

        'Imprime linea liquidacion simple
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "___________________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 280)

        Dim total As Double
        Dim decimales As String
        Dim numeros As Integer
        Dim distancia As Integer
        total = txtTotal.Text
        numeros = Len(total)
        If total > 0 And total < 10 Then
            distancia = 3
        ElseIf total > 9 And total < 100 Then
            distancia = 4
        ElseIf total > 99 And total < 1000 Then
            distancia = 5
        ElseIf total > 999 And total < 10000 Then
            distancia = 6
        ElseIf total > 9999 And total < 100000 Then
            distancia = 7
        ElseIf total > 99999 And total > 1000000 Then
            distancia = 8
        ElseIf total > 999999 And total > 10000000 Then
            distancia = 9
        End If
        decimales = Mid((txtTotal.Text), distancia, 2)
        Dim Cantidad As String = Num2Text(Int(total)) & " PESOS " & decimales & "/100 M.N"
        'Imprime total a liquidar
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Total a Liquidar: $" & txtTotal.Text & ".00")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 95, 295)

        printFont = New System.Drawing.Font("Arial", 7)
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "(" & Cantidad & ")")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 20, 310)

        printFont = New System.Drawing.Font("Arial", 8)
        'Imprime linea liquidacion doble 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "___________________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 310)

        'Imprime linea liquidacion doble 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "___________________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 312)

        'Imprime linea operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "______________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 360)

        'Imprime firma operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Conforme Operador")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 30, 375)

        'Imprime linea liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "______________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 155, 360)

        'Imprime firma liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtAnalista.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 145, 375)
    End Sub
    Private Sub prt_PapeletaCuotaTiket(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        ' Este evento se produce cada vez que se va a imprimir una página
        Dim lineHeight As Single
        Dim yPos As Single = e.MarginBounds.Top
        Dim leftMargin As Single = e.MarginBounds.Left
        Dim printFont As System.Drawing.Font
        Dim sb As System.Text.StringBuilder

        ' Asignar el tipo de letra
        printFont = New System.Drawing.Font("Arial", 10, FontStyle.Bold)
        lineHeight = printFont.GetHeight(e.Graphics)
        '
        'ENCABEZADO
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Consorcio Optra")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 100, 5)

        printFont = New System.Drawing.Font("Arial", 8)
        yPos += lineHeight
        sb = New System.Text.StringBuilder

        Dim Empresa As String = BuscarStrDatoCitra("SELECT CVALORCL01 FROM MGW10020 C INNER JOIN MGW10002 A ON C.CIDVALOR01=A.CIDVALOR02 WHERE A.cCODIGOC01='" & txtRuta.Text.Trim & "'")
        sb.AppendFormat("{0} ", Empresa)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 20)

        printFont = New System.Drawing.Font("Arial", 8)
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Ticket de Liquidación")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 35)

        printFont = New System.Drawing.Font("Arial", 8)
        'Imprime el Operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Operador: " & txtOperador.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 60)


        'Imprime el autobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Autobus: " & txtAutobus.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 75)

        'Imprime la Ruta
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", BuscarStrDatoCitra("Rutas", "Nombre", "cCodigoV01='" & txtRuta.Text.Trim & "'"))
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 90)

        'Imprime la fecha
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Fecha: " & datFecha.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 105)

        'Imprime las vueltas
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Vueltas: " & txtVueltas.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 120)

        'Imprime el tipo
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Tipo: Por Cuota")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 135)

        'Imprime el folio
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Folio: " & liq.IdLiquidacion)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 150)

        'Imprime encabezado boletos


        'Imprime linea liquidacion simple
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "___________________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 190)

        Dim total As Double
        Dim decimales As String
        Dim numeros As Integer
        Dim distancia As Integer
        total = txtTotal.Text
        numeros = Len(total)
        If total > 0 And total < 10 Then
            distancia = 3
        ElseIf total > 9 And total < 100 Then
            distancia = 4
        ElseIf total > 99 And total < 1000 Then
            distancia = 5
        ElseIf total > 999 And total < 10000 Then
            distancia = 6
        ElseIf total > 9999 And total < 100000 Then
            distancia = 7
        ElseIf total > 99999 And total > 1000000 Then
            distancia = 8
        ElseIf total > 999999 And total > 10000000 Then
            distancia = 9
        End If
        decimales = Mid((txtTotal.Text), distancia, 2)
        Dim Cantidad As String = Num2Text(Int(total)) & " PESOS " & decimales & "/100 M.N"
        'Imprime total a liquidar
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Total a Liquidar: $" & txtTotal.Text & ".00")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 95, 205)

        printFont = New System.Drawing.Font("Arial", 7)
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "(" & Cantidad & ")")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 20, 220)

        printFont = New System.Drawing.Font("Arial", 8)
        'Imprime linea liquidacion doble 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "___________________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 220)

        'Imprime linea liquidacion doble 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "___________________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 222)

        'Imprime linea operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "______________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 270)

        'Imprime firma operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Conforme Operador")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 30, 285)

        'Imprime linea liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "______________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 155, 270)

        'Imprime firma liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtAnalista.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 145, 285)
    End Sub
    Private Sub prt_PapeletaBoletos(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        ' Este evento se produce cada vez que se va a imprimir una página
        Dim lineHeight As Single
        Dim yPos As Single = e.MarginBounds.Top
        Dim leftMargin As Single = e.MarginBounds.Left
        Dim printFont As System.Drawing.Font
        Dim sb As System.Text.StringBuilder

        ' Asignar el tipo de letra
        printFont = New System.Drawing.Font("Arial", 12, FontStyle.Bold)
        lineHeight = printFont.GetHeight(e.Graphics)
        '
        'ENCABEZADO
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Coordinado Autobuses Urbanos y Suburbanos de León, S.A. de C.V.")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 140, 12)
        printFont = New System.Drawing.Font("Arial", 11)

        yPos += lineHeight
        sb = New System.Text.StringBuilder

        Dim Empresa As String = BuscarStrDatoCitra("SELECT CVALORCL01 FROM MGW10020 C INNER JOIN MGW10002 A ON C.CIDVALOR01=A.CIDVALOR02 WHERE A.cCODIGOC01='" & txtRuta.Text.Trim & "'")
        sb.AppendFormat("{0} ", "Empresa: " & Empresa)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 238, 42)
        printFont = New System.Drawing.Font("Arial", 10)

        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Papeleta de Liquidación")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 315, 62)

        printFont = New System.Drawing.Font("Arial", 10)

        'Imprime el Operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Operador: " & txtOperador.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 35, 140)


        'Imprime el autobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Autobus: " & txtAutobus.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 35, 175)

        'Imprime la Ruta
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", BuscarStrDatoCitra("Rutas", "Nombre", "cCodigoV01='" & txtRuta.Text.Trim & "'"))
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 35, 210)

        'Imprime la fecha
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Fecha: " & datFecha.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 635, 140)

        'Imprime las vueltas
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Vueltas: " & txtVueltas.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 635, 175)

        'Imprime el tipo
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Tipo: Por Boletaje")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 635, 210)

        'Imprime el folio
        'yPos += lineHeight
        'sb = New System.Text.StringBuilder
        'sb.AppendFormat("{0} ", "Folio: " & liq.CidLiquida)
        'e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 710, 63)

        'Imprime encabezado boletos


        'Imprime linea 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "_____________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 259)

        'Imprime encabezado boletos 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Serie           Del                 Al                 Total                Pagobus Preferencial      Pagobus General")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 122, 273)

        'Imprime linea 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "_____________________________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 273)

        'Imprime serie
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtSerie.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 131, 289)

        'Imprime Inicial
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtInicial.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 189, 289)

        'Imprime final
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtFinal.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 275, 289)

        'Imprime total boletos
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtTotalBoletos.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 370, 289)

        'Imprime pagobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtPreferencial.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 471, 289)

        'Imprime pagobus pendiente
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtGeneral.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 612, 289)

        Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - (CDbl(txtPreferencial.Text) + CDbl(txtGeneral.Text))

        'Imprime boletos realmente vendidos
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Boletos Vendidos: " & TotalBoletos)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 300, 309)

        'Imprime linea liquidacion simple
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 229, 332)

        Dim total As Double
        Dim decimales As String
        Dim numeros As Integer
        Dim distancia As Integer
        total = txtTotal.Text
        numeros = Len(total)
        If total > 0 And total < 10 Then
            distancia = 3
        ElseIf total > 9 And total < 100 Then
            distancia = 4
        ElseIf total > 99 And total < 1000 Then
            distancia = 5
        ElseIf total > 999 And total < 10000 Then
            distancia = 6
        ElseIf total > 9999 And total < 100000 Then
            distancia = 7
        ElseIf total > 99999 And total > 1000000 Then
            distancia = 8
        ElseIf total > 999999 And total > 10000000 Then
            distancia = 9
        End If
        decimales = Mid((txtTotal.Text), distancia, 2)
        Dim Cantidad As String = Num2Text(Int(total)) & " PESOS " & decimales & "/100 M.N"
        'Imprime total a liquidar
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Total a Liquidar: $" & txtTotal.Text & ".00" & "          (" & Cantidad & ")")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 122, 350)

        'Imprime linea liquidacion doble 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 229, 356)

        'Imprime linea liquidacion doble 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 229, 359)

        'Imprime linea operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 123, 406)

        'Imprime firma operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Conforme Operador")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 140, 420)

        'Imprime linea liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 490, 406)

        'Imprime firma liquidador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtAnalista.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 507, 420)

    End Sub
    Sub CargaOperadoresGlobal()
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        dgNombres.Rows.Clear()

        Dim strNombre As String
        strNombre = UCase(txtBuscarNombre.Text.Trim)
        strNombre = "%" & strNombre.Replace(" ", "%") & "%"

        Dim cnconn As New SqlConnection
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            cnconn.ConnectionString = CitraConnection
            Dim strSql As String = "Select Codigo,Nombre FROM OperadoresGlobal WHERE UPPER(Nombre)  Like '" & strNombre & "' " & mstrCondicion & " COLLATE SQL_LATIN1_GENERAL_CP1_CI_AI AND EstadoEmpleado<>'B'"

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql


            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                dgNombres.Rows.Add(rdBuscar("Codigo").ToString.Trim, rdBuscar("Nombre").ToString.Trim)
                dgNombres.CurrentCell = dgNombres.Rows(0).Cells(1)
            Loop

        Catch ex As SqlException
            MessageBox.Show(ex.Message, "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try


    End Sub
    Sub CargaLiquidadores()
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        dgLiquidadores.Rows.Clear()

        Dim strNombre As String
        strNombre = UCase(txtBuscaLiquidador.Text.Trim)
        strNombre = "%" & strNombre.Replace(" ", "%") & "%"

        Dim cnconn As New SqlConnection
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            cnconn.ConnectionString = InitialConnection
            Dim strSql As String = "Select Codigo,NombreCompleto FROM Liquidadores WHERE UPPER(NombreCompleto)  Like '" & strNombre & "' " & mstrCondicion & " COLLATE SQL_LATIN1_GENERAL_CP1_CI_AI AND EstadoEmpleado<>'B'"

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql


            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                dgLiquidadores.Rows.Add(rdBuscar("Codigo").ToString.Trim, rdBuscar("NombreCompleto").ToString.Trim)
                'dgLiquidadores.CurrentCell = dgNombres.Rows(0).Cells(1)
            Loop

        Catch ex As SqlException
            MessageBox.Show(ex.Message, "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try


    End Sub


    Private Sub txtAutobus_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtAutobus.KeyDown
        If e.KeyCode = Keys.F3 Then
            panelRutas.Visible = False
            panelNombres.Visible = False

            panelBuses.Visible = True
            txtBuscarBus.Focus()
            txtBuscarBus.Clear()
            txtBuscarBus.SelectAll()
        End If
    End Sub

    Private Sub txtAutobus_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAutobus.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            Dim Id As Integer = BuscarIntDatoCitra("Autobuses", "IdAutobus", "NoEconomico='" & txtAutobus.Text.Trim & "' and estatus=1")
            If Id > 0 Then
                txtCidClien01.Text = Id
                txtTotal.Text = Format(CDbl(txtTotalBoletos.Text) * 8, "###,###.#0")
                If radioPreLiquidacion.Checked = True Then
                    If txtSerie.Text = "" Then
                        MsgBox("Debes indicar la serie del boletaje", MsgBoxStyle.Exclamation, "Aviso")
                        txtSerie.Focus()
                        txtSerie.SelectAll()
                    Else
                        BuscarBoletos()
                        txtFinal.Text = 0
                        txtTotalBoletos.Text = 0
                        txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.IdAutobus=" & Id)
                        txtCodigoOperador.Focus()
                        txtCodigoOperador.SelectAll()
                    End If
                Else
                    txtFinal.Text = 0
                    txtTotalBoletos.Text = 0
                    txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.IdAutobus=" & Id)
                    txtCodigoOperador.Focus()
                    txtCodigoOperador.SelectAll()
                End If
            Else
                MsgBox("El autobus no existe o se encuentra inactivo", MsgBoxStyle.Exclamation, "Aviso")
                txtAutobus.SelectAll()
            End If

        End If
    End Sub

    Private Sub txtAutobus_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtAutobus.Leave
        'Busca ultimo operador
        If chScanner.Checked = False Then
            Dim UltimoOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM Liquidacion Where IdAutobus=" & txtCidClien01.Text & " ORDER BY IdLiquidacion DESC")
            If UltimoOperador > 0 Then
                txtCodigoOperador.Text = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                txtOperador.Text = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                BuscaPagobus()
            End If
        End If
       



    End Sub

    Private Sub txtAutobus_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAutobus.TextChanged

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub txtFolio_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtFolio.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            datFecha.Focus()
        End If
    End Sub

    Private Sub txtFolio_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFolio.TextChanged
        Actualizar()
    End Sub

    Private Sub datFecha_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles datFecha.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            txtAnalista.Focus()
            txtAnalista.SelectAll()
        End If
    End Sub

    Private Sub datFecha_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles datFecha.ValueChanged

    End Sub

    Private Sub txtAnalista_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = Chr(Keys.Enter) Then
            txtCodigoOperador.Focus()
            txtCodigoOperador.SelectAll()
        End If
    End Sub

    Private Sub txtAnalista_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub txtOperador_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOperador.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            txtAutobus.Focus()
            txtAutobus.SelectAll()
        End If
    End Sub

    Private Sub txtOperador_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtOperador.TextChanged

    End Sub

    Private Sub lstAlmacen_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub lstConcepto_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = Chr(Keys.Enter) Then
            txtCodigoLiquidador.Focus()
            txtCodigoLiquidador.SelectAll()
        End If
    End Sub

    Private Sub lstConcepto_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ToolStripButton5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub RadButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        TotalLiquidacion()

        chImprimir.Checked = True

        Es_Buscado = False

        txtFolio.Text = -1
        txtFolio.Text = 0
        Application.DoEvents()


    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub

    Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Close()

    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub

    Private Sub RadButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub

    Private Sub ActualToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Primero verifica si esta guardada


    End Sub

    Private Sub IngresosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'frmRIngresos.ShowDialog()

    End Sub

    Private Sub LiquidaciónToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ' frmRLiquidacion.ShowDialog()


    End Sub

    Private Sub ToolStripButton6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    End Sub

    Private Sub ConcentraciónToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'frmRConcentracion.ShowDialog()

    End Sub

    Private Sub dgLiquidacion_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)

    End Sub

    Private Sub txtBuscarNombre_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtBuscarNombre.KeyDown

    End Sub

    Private Sub txtBuscarNombre_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtBuscarNombre.KeyPress
        If radioPreLiquidacion.Checked = True Then
            If e.KeyChar = Chr(Keys.Enter) Then
                panelNombres.Visible = False

                Dim Nombre As String = dgNombres.CurrentRow.Cells(1).Value.ToString.Trim
                Dim Codigo As String = dgNombres.CurrentRow.Cells(0).Value.ToString.Trim
                txtCodigoOperador.Text = Codigo
                txtOperador.Text = Nombre
                txtFinal.Focus()
                txtFinal.SelectAll()
                BuscaPagobus()
            ElseIf e.KeyChar = Chr(Keys.Escape) Then
                panelNombres.Visible = False
            End If
        Else
            If e.KeyChar = Chr(Keys.Enter) Then
                panelNombres.Visible = False

                Dim Nombre As String = dgNombres.CurrentRow.Cells(1).Value.ToString.Trim
                Dim Codigo As String = dgNombres.CurrentRow.Cells(0).Value.ToString.Trim
                txtCodigoOperador.Text = Codigo
                txtOperador.Text = Nombre
                txtVueltas.Focus()
                txtVueltas.SelectAll()
                BuscaPagobus()
            ElseIf e.KeyChar = Chr(Keys.Escape) Then
                panelNombres.Visible = False
            End If
        End If

    End Sub

    Private Sub txtBuscarNombre_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscarNombre.TextChanged
        CargaOperadoresGlobal()
    End Sub

    Private Sub btnBuscarLiquidador_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
       

    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If chScanner.Checked = False Then
            panelRutas.Visible = False
            panelBuses.Visible = False
            panelNombres.BringToFront()
            panelNombres.Visible = True
            PanelLiquidadores.Visible = False
            OrigenNombre = "O"
            txtBuscarNombre.Focus()
            txtBuscarNombre.Clear()
            txtBuscarNombre.SelectAll()
        Else
            Dim CardID As Integer
            Dim CustomID As Integer

            result = BS_ReadCardIDEx(handle_Renamed, CardID, CustomID)
            lblStatusLiquidacion.Text = "Leyendo tarjeta..."
            Application.DoEvents()
            'tbxMessage.AppendText("Leyendo tarjeta..." & vbNewLine)
            If result <> 0 Then
                lblStatusLiquidacion.Text = "El tiempo de espera expiró. Error : " & result
                Application.DoEvents()
                'tbxMessage.AppendText("El tiempo de espera expiró. Error : " & result & vbNewLine)
                Exit Sub
            End If

            Dim CodigoTarjeta As String = CardID

            Dim CodigoOperador As String = BuscarStrDatoCitra("SELECT Codigo FROM Tarjetas WHERE CodigoTarjeta='" & CodigoTarjeta & "'")
            Dim IdOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM Tarjetas WHERE CodigoTarjeta='" & CodigoTarjeta & "'")
            If IdOperador > 0 Then
                lblStatusLiquidacion.Text = "Se identifico correctamente"
                Application.DoEvents()
                'tbxMessage.AppendText("Se identifico correctamente" & vbNewLine)
            Else
                lblStatusLiquidacion.Text = "La tarjeta " & CodigoTarjeta & " se identifico, pero no ha sido asignada"
                Application.DoEvents()
                'tbxMessage.AppendText("La tarjeta identifico, pero no ha sido asignada" & vbNewLine)
                Exit Sub
            End If

            Dim FechaActual As Date = Now()
            Dim Vencimiento As Date = BuscarDateDatoCitra("SELECT TerminoVigencia FROM Tarjetas WHERE CodigoTarjeta='" & CodigoTarjeta & "'")

            If Vencimiento < FechaActual Then
                lblStatusLiquidacion.Text = "La tarjeta ya esta vencida..."
                Application.DoEvents()
                Exit Sub
            End If

            Dim EstadoEmpleado As String = BuscarStrDatoCitra("SELECT EstadoEmpleado FROM OperadoresGlobal WHERE Codigo='" & CodigoOperador & "'")
            If EstadoEmpleado = "B" Then
                lblStatusLiquidacion.Text = "El operador es Baja..."
                Application.DoEvents()
                Exit Sub
            End If

            txtOperador.Text = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE Codigo='" & CodigoOperador & "'")
            txtCodigoOperador.Text = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE Codigo='" & CodigoOperador & "'")
            Application.DoEvents()
        End If
        

    End Sub

    Private Sub dgNombres_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgNombres.CellDoubleClick
        If radioPreLiquidacion.Checked = True Then
            panelNombres.Visible = False
            Dim Nombre As String = dgNombres.CurrentRow.Cells(1).Value.ToString.Trim
            Dim Codigo As String = dgNombres.CurrentRow.Cells(0).Value.ToString.Trim
            If OrigenNombre = "L" Then
                txtCodigoLiquidador.Text = Codigo
                txtAnalista.Text = Nombre
                txtAutobus.Focus()
                txtAutobus.SelectAll()
            ElseIf OrigenNombre = "O" Then

                txtCodigoOperador.Text = Codigo
                txtOperador.Text = Nombre
                txtFinal.Focus()
                txtFinal.SelectAll()
                BuscaPagobus()
            End If
        Else
            panelNombres.Visible = False
            Dim Nombre As String = dgNombres.CurrentRow.Cells(1).Value.ToString.Trim
            Dim Codigo As String = dgNombres.CurrentRow.Cells(0).Value.ToString.Trim
            If OrigenNombre = "L" Then
                txtCodigoLiquidador.Text = Codigo
                txtAnalista.Text = Nombre
                txtAutobus.Focus()
                txtAutobus.SelectAll()
            ElseIf OrigenNombre = "O" Then

                txtCodigoOperador.Text = Codigo
                txtOperador.Text = Nombre
                txtVueltas.Focus()
                txtVueltas.SelectAll()
                BuscaPagobus()
            End If
        End If


    End Sub
    Private Sub dgNombres_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgNombres.KeyPress

    End Sub

    Private Sub txtCodigoLiquidador_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        
    End Sub

    Private Sub txtCodigoLiquidador_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        
    End Sub
    Private Sub txtCodigoLiquidador_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub txtCodigoOperador_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCodigoOperador.KeyDown
        If e.KeyCode = Keys.F3 Then
            panelRutas.Visible = False
            panelBuses.Visible = False
            panelNombres.BringToFront()
            panelNombres.Visible = True
            OrigenNombre = "O"
            txtBuscarNombre.Focus()
            txtBuscarNombre.Clear()
            txtBuscarNombre.SelectAll()
        End If
    End Sub

    Private Sub txtCodigoOperador_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCodigoOperador.KeyPress
        If radioPreLiquidacion.Checked = True Then
            If e.KeyChar = Chr(Keys.Enter) Then
                Dim Nombre As String = BuscarStrDatoCitra("OperadoresGlobal", "Nombre", "Codigo='" & txtCodigoOperador.Text.Trim & "' AND EstadoEmpleado<>'B'")
                If Nombre <> "" Then
                    txtOperador.Text = Nombre
                    txtFinal.Focus()
                    txtFinal.SelectAll()
                Else
                    MsgBox("El codigo del Operador indicado, no existe o se encuentra inactivo", MsgBoxStyle.Exclamation, "Aviso")
                    txtOperador.Clear()
                    txtCodigoOperador.SelectAll()
                End If
            End If
        Else
            If e.KeyChar = Chr(Keys.Enter) Then
                Dim Nombre As String = BuscarStrDatoCitra("OperadoresGlobal", "Nombre", "Codigo='" & txtCodigoOperador.Text.Trim & "' AND EstadoEmpleado<>'B'")
                If Nombre <> "" Then
                    txtOperador.Text = Nombre
                    txtVueltas.Focus()
                    txtVueltas.SelectAll()
                Else
                    MsgBox("El codigo del Operador indicado, no existe o se encuentra inactivo", MsgBoxStyle.Exclamation, "Aviso")
                    txtOperador.Clear()
                    txtCodigoOperador.SelectAll()
                End If
            End If
        End If

    End Sub

    Sub BuscarBoletos()
        Dim Boletos As Double = BuscarDblDatoCitra("Select Inicial FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "' and Final-Inicial>1")
        txtInicial.Text = Boletos
        txtCidBoleto.Text = BuscarIntDatoCitra("Select idboleto FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
        If Boletos = 0 Then
            MsgBox("La serie indicada no cuenta con existencia de boletos", MsgBoxStyle.Exclamation, "Aviso")
        End If
    End Sub

    Private Sub txtCodigoOperador_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCodigoOperador.Leave
        BuscaPagobus()
    End Sub
    Private Sub txtCodigoOperador_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCodigoOperador.TextChanged

    End Sub

    Private Sub txtSerie_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSerie.KeyPress


        If e.KeyChar = Chr(Keys.Enter) Then
            If txtCidClien01.Text <> 0 Then
                BuscarBoletos()
                txtFinal.Text = 0
                txtTotalBoletos.Text = 0
                txtFinal.Focus()
                txtFinal.SelectAll()
            Else
                txtCodigoLiquidador.Focus()
                txtCodigoLiquidador.SelectAll()
            End If
        End If
    End Sub

    Private Sub txtInicial_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInicial.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            If txtSerie.Text = "" Then
                MsgBox("Se debe indicar la serie", MsgBoxStyle.Exclamation, "Aviso")
                txtInicial.Text = 0
                txtSerie.Focus()
                txtSerie.SelectAll()
            Else
                If Not IsNumeric(txtInicial.Text) Then
                    MsgBox("El valor indicado es incorrecto", MsgBoxStyle.Exclamation, "Aviso")
                    BuscarBoletos()
                    txtInicial.Focus()
                    txtInicial.SelectAll()
                Else
                    txtTotalBoletos.Text = CDbl(txtFinal.Text) - CDbl(txtInicial.Text)
                    Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - (CDbl(txtGeneral.Text) + CDbl(txtPreferencial.Text))
                    txtTotal.Text = Format(CDbl(TotalBoletos) * 9, "###,###.#0")
                    txtFinal.Focus()

                End If
            End If
        End If

    End Sub


    Private Sub txtInicial_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtInicial.TextChanged

    End Sub

    Private Sub txtFinal_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtFinal.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            If txtSerie.Text = "" Then
                MsgBox("Se debe indicar la serie", MsgBoxStyle.Exclamation, "Aviso")
                txtFinal.Text = 0
                txtSerie.Focus()
                txtSerie.SelectAll()
            Else
                If Not IsNumeric(txtFinal.Text) Then
                    MsgBox("El valor indicado es incorrecto", MsgBoxStyle.Exclamation, "Aviso")
                    txtFinal.Text = 0
                    txtFinal.Focus()
                    txtFinal.SelectAll()
                Else
                    Dim FolioFinal As Double = BuscarDblDatoCitra("Select Final FROM KARDEX WHERE idBoleto=" & txtCidBoleto.Text)
                    If CDbl(txtFinal.Text) > FolioFinal Then
                        MsgBox("La numeracion final excede la numeración existente", MsgBoxStyle.Exclamation, "Aviso")
                        txtFinal.Text = FolioFinal
                    End If

                    txtTotalBoletos.Text = CDbl(txtFinal.Text) - CDbl(txtInicial.Text)
                    Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - (CDbl(txtGeneral.Text) + CDbl(txtPreferencial.Text))
                    txtTotal.Text = Format(CDbl(TotalBoletos) * 9, "###,###.#0")
                    txtPreferencial.Focus()
                End If
            End If
        End If

    End Sub

    Private Sub txtFinal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFinal.TextChanged

    End Sub

    Private Sub txtPagobus_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPreferencial.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            If txtSerie.Text = "" Then
                MsgBox("Se debe indicar la serie", MsgBoxStyle.Exclamation, "Aviso")
                txtPreferencial.Text = 0
                txtSerie.Focus()
                txtSerie.SelectAll()
            Else
                If Not IsNumeric(txtPreferencial.Text) Then
                    MsgBox("El valor indicado es incorrecto", MsgBoxStyle.Exclamation, "Aviso")
                    txtPreferencial.Text = 0
                    txtPreferencial.SelectAll()
                Else
                    txtTotalBoletos.Text = CDbl(txtFinal.Text) - CDbl(txtInicial.Text)
                    Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - (CDbl(txtGeneral.Text) + CDbl(txtPreferencial.Text))
                    txtTotal.Text = Format(CDbl(TotalBoletos) * 9, "###,###.#0")
                    txtGeneral.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub txtPagobus_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPreferencial.TextChanged

    End Sub

    Private Sub txtPagobusPendiente_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtGeneral.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            If txtSerie.Text = "" Then
                MsgBox("Se debe indicar la serie", MsgBoxStyle.Exclamation, "Aviso")
                txtPreferencial.Text = 0
                txtSerie.Focus()
                txtSerie.SelectAll()
            Else
                If Not IsNumeric(txtGeneral.Text) Then
                    MsgBox("El valor indicado es incorrecto", MsgBoxStyle.Exclamation, "Aviso")
                    txtGeneral.Text = 0
                    txtGeneral.SelectAll()
                Else
                    txtTotalBoletos.Text = CDbl(txtFinal.Text) - CDbl(txtInicial.Text)
                    Dim TotalBoletos As Double = CDbl(txtTotalBoletos.Text) - (CDbl(txtGeneral.Text) + CDbl(txtPreferencial.Text))
                    txtTotal.Text = Format(CDbl(TotalBoletos) * 9, "###,###.#0")
                    txtVueltas.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub txtPagobusPendiente_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtGeneral.TextChanged

    End Sub

    Private Sub ToolStripDropDownButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub dgNombres_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgNombres.CellContentClick

    End Sub

    Private Sub panelNombres_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles panelNombres.Paint

    End Sub

    Private Sub txtTotalBoletos_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotalBoletos.TextChanged

    End Sub

    Private Sub txtVueltas_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVueltas.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            If radioPreLiquidacion.Checked = True Then
                GuardarPorBoletaje()
            Else
                txtTotal.SelectAll()
                txtTotal.Focus()
            End If
        End If

    End Sub

    Private Sub txtVueltas_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtVueltas.TextChanged

    End Sub

    Private Sub chImprimir_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chImprimir.CheckedChanged

    End Sub

    Private Sub ProductividadToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'frmRProductividad.ShowDialog()
    End Sub

    Private Sub ResultadosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'frmRResultados.ShowDialog()
    End Sub

    Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        panelRutas.Visible = False
        panelNombres.Visible = False

        panelBuses.Visible = True
        txtBuscarBus.Focus()
        txtBuscarBus.Clear()
        txtBuscarBus.SelectAll()
    End Sub
    Private Sub dgBuses_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgBuses.CellDoubleClick
        panelBuses.Visible = False
        Dim Nombre As String = dgBuses.CurrentRow.Cells(1).Value.ToString.Trim
        txtAutobus.Text = Nombre
        txtCidClien01.Text = dgBuses.CurrentRow.Cells(2).Value
        txtTotal.Text = Format(CDbl(txtTotalBoletos.Text) * 8, "###,###.#0")
        If txtSerie.Text = "" Then
            MsgBox("Debes indicar la serie del boletaje", MsgBoxStyle.Exclamation, "Aviso")
            txtSerie.Focus()
            txtSerie.SelectAll()
        Else
            txtInicial.Text = BuscarDblDatoCitra("Select Inicial FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
            txtCidBoleto.Text = BuscarIntDatoCitra("Select IdBoleto FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
            txtFinal.Text = 0
            txtTotalBoletos.Text = 0
            txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.NoEconomico='" & Nombre & "'")
            If chScanner.Checked = False Then
                Dim UltimoOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM Liquidacion Where IdAutobus=" & txtCidClien01.Text & " ORDER BY IdLiquidacion DESC")
                If UltimoOperador > 0 Then
                    txtCodigoOperador.Text = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                    txtOperador.Text = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                    BuscaPagobus()
                    txtFinal.Focus()
                    txtFinal.SelectAll()
                Else
                    txtCodigoOperador.Focus()
                    txtCodigoOperador.SelectAll()
                End If
            Else
                txtFinal.Focus()
                txtFinal.SelectAll()
            End If
           


        End If

    End Sub
    Private Sub dgBuses_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgBuses.KeyPress

    End Sub

    Private Sub txtBuscarBus_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtBuscarBus.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            panelBuses.Visible = False
            Dim Nombre As String = dgBuses.CurrentRow.Cells(1).Value.ToString.Trim
            txtAutobus.Text = Nombre
            txtCidClien01.Text = dgBuses.CurrentRow.Cells(2).Value
            txtTotal.Text = Format(CDbl(txtTotalBoletos.Text) * 8, "###,###.#0")
            If txtSerie.Text = "" Then
                MsgBox("Debes indicar la serie del boletaje", MsgBoxStyle.Exclamation, "Aviso")
                txtSerie.Focus()
                txtSerie.SelectAll()
            Else
                txtInicial.Text = BuscarDblDatoCitra("Select Inicial FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
                txtCidBoleto.Text = BuscarIntDatoCitra("Select IdBoleto FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
                txtFinal.Text = 0
                txtTotalBoletos.Text = 0
                txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.NoEconomico='" & Nombre & "'")
                If chScanner.Checked = False Then
                    Dim UltimoOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM Liquidacion Where IdAutobus=" & txtCidClien01.Text & " ORDER BY IdLiquidacion DESC")
                    If UltimoOperador > 0 Then
                        txtCodigoOperador.Text = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                        txtOperador.Text = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                        BuscaPagobus()

                        txtFinal.Focus()
                        txtFinal.SelectAll()
                    Else
                        txtCodigoOperador.Focus()
                        txtCodigoOperador.SelectAll()
                    End If
                Else
                    txtFinal.Focus()
                    txtFinal.SelectAll()
                End If
               

            End If
        ElseIf e.KeyChar = Chr(Keys.Escape) Then
            panelBuses.Visible = False
        End If

    End Sub

    Private Sub txtBuscarBus_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscarBus.TextChanged
        CargaBuses()
    End Sub


    Private Sub dgBuses_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgBuses.CellContentClick

    End Sub

    Private Sub txtSerie_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSerie.TextChanged
        Dim texto As String = txtSerie.Text
        If texto = "" Then
            Exit Sub
        End If
        Dim longtext As Integer = Len(texto)
        Dim caracter As String = Mid(texto, longtext, 1)
        Dim anterior As String = Mid(texto, 1, longtext - 1)
        If longtext = 1 Then
            txtSerie.Text = UCase(caracter)
        Else
            txtSerie.Text = anterior & UCase(caracter)

        End If
        txtSerie.Select(longtext + 1, longtext + 1)
    End Sub

    Private Sub ToolStripButton3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'frmRutas.ShowDialog()
    End Sub



    Private Sub txtRuta_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub txtBuscarRuta_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtBuscarRuta.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            panelRutas.Visible = False
            Dim Nombre As String = dgRuta.CurrentRow.Cells(0).Value.ToString.Trim
            txtRuta.Text = Nombre

            txtFinal.Focus()
            txtFinal.SelectAll()

        ElseIf e.KeyChar = Chr(Keys.Escape) Then
            panelRutas.Visible = False
        End If
    End Sub

    Private Sub txtBuscarRuta_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscarRuta.TextChanged
        CargaRutas()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        panelBuses.Visible = False
        panelNombres.Visible = False

        panelRutas.Visible = True
        txtBuscarRuta.Focus()
        txtBuscarRuta.Clear()
        txtBuscarRuta.SelectAll()
    End Sub

    Private Sub dgRuta_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgRuta.CellContentClick

    End Sub

    Private Sub dgRuta_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgRuta.CellDoubleClick
        panelRutas.Visible = False
        Dim Nombre As String = dgRuta.CurrentRow.Cells(0).Value.ToString.Trim
        txtRuta.Text = Nombre


        txtFinal.Focus()
        txtFinal.SelectAll()

    End Sub

    Private Sub dgBuses_ImeModeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgBuses.ImeModeChanged

    End Sub

    Private Sub dgRuta_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgRuta.KeyDown
        If e.KeyCode = Keys.Enter Then
            panelRutas.Visible = False

            Dim nombre As String = ""
            nombre = dgRuta.Item(0, dgRuta.CurrentCell.RowIndex).Value

            txtRuta.Text = nombre
            txtFinal.Focus()
            txtFinal.SelectAll()

        ElseIf e.KeyCode = Keys.Escape Then
            panelRutas.Visible = False
        End If
    End Sub

    Private Sub dgRuta_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgRuta.KeyPress

    End Sub

    Private Sub PapeletaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub dgNombres_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgNombres.KeyDown
        If e.KeyCode = Keys.Enter Then
            panelNombres.Visible = False
            Dim Nombre As String
            Dim Codigo As String

            Nombre = CStr(dgNombres.Item(1, dgNombres.CurrentCell.RowIndex).Value)
            Codigo = CStr(dgNombres.Item(0, dgNombres.CurrentCell.RowIndex).Value)

            If OrigenNombre = "L" Then
                txtCodigoLiquidador.Text = Codigo
                txtAnalista.Text = Nombre
                txtCodigoOperador.Focus()
                txtCodigoOperador.SelectAll()

            ElseIf OrigenNombre = "O" Then
                txtCodigoOperador.Text = Codigo
                txtOperador.Text = Nombre
                txtAutobus.Focus()
                txtAutobus.SelectAll()
            End If
        ElseIf e.KeyCode = Keys.Escape Then
            panelNombres.Visible = False
        End If
    End Sub

    Private Sub dgBuses_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgBuses.KeyDown
        If e.KeyCode = Keys.Enter Then
            panelBuses.Visible = False

            Dim Nombre As String
            Nombre = CStr(dgBuses.Item(1, dgBuses.CurrentCell.RowIndex).Value)
            txtCidClien01.Text = CInt(dgBuses.Item(2, dgBuses.CurrentCell.RowIndex).Value)

            txtAutobus.Text = Nombre
            txtTotal.Text = Format(CDbl(txtTotalBoletos.Text) * 8, "###,###.#0")
            If txtSerie.Text = "" Then
                MsgBox("Debes indicar la serie del boletaje", MsgBoxStyle.Exclamation, "Aviso")
                txtSerie.Focus()
                txtSerie.SelectAll()
            Else
                txtInicial.Text = BuscarDblDatoCitra("Select Inicial FROM KARDEX WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
                txtCidBoleto.Text = BuscarIntDatoCitra("Select IdBoleto FROM Kardex WHERE IdAutobus=" & txtCidClien01.Text.Trim & " AND Serie='" & UCase(txtSerie.Text.Trim) & "'")
                txtFinal.Text = 0
                txtTotalBoletos.Text = 0
                txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.NoEconomico='" & Nombre & "'")
                Dim UltimoOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM Liquidacion Where IdAutobus=" & txtCidClien01.Text & " ORDER BY IdLiquidacion DESC")
                If UltimoOperador > 0 Then
                    txtCodigoOperador.Text = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                    txtOperador.Text = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE IdEmpleado=" & UltimoOperador)
                    txtFinal.Focus()
                    txtFinal.SelectAll()
                Else
                    txtCodigoOperador.Focus()
                    txtCodigoOperador.SelectAll()
                End If

            End If
        ElseIf e.KeyCode = Keys.Escape Then
            panelBuses.Visible = False
        End If
    End Sub

    Private Sub ToolStripButton7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'frmTarjeta.ShowDialog()
    End Sub

    Private Sub NuevaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuevaToolStripMenuItem.Click
        Dim FechaLiquidacion As String = datFecha.Value.ToString("MM/dd/yyyy")
        TotalLiquidacion()

        chImprimir.Checked = True

        Dim Liquidador As String = txtAnalista.Text
        Dim CodigoLiquidador As String = txtCodigoLiquidador.Text

        Es_Buscado = False
        txtFolio.Text = -1
        txtFolio.Text = 0
        Application.DoEvents()


        txtAnalista.Text = Liquidador
        txtCodigoLiquidador.Text = CodigoLiquidador
    End Sub

    Private Sub BuscarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim strResult As String
        Dim fBusqueda As New frmBuscarLiquidaciones

        fBusqueda.ShowDialog()

        If fBusqueda.DialogResult = Windows.Forms.DialogResult.OK Then
            strResult = fBusqueda.Valor

            If strResult <> "" Then
                txtFolio.Text = strResult
                Es_Buscado = True
                'Actualizar()
            End If
        End If
    End Sub

    Private Sub EliminarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Eliminar()

    End Sub
    Sub Eliminar()
        Dim ID As Integer = BuscarIntDatoCitra("Liquidacion", "IdLiquidacion", "IdLiquidacion=" & txtFolio.Text)
        If ID = 0 Then
            MsgBox("No se ha seleccionado ningun documento", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If DiaTrabajado(datFecha.Value) = True Then
            MsgBox("El dia " & datFecha.Text & " ya ha sido archivado", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Dim resp As Integer
        resp = MsgBox("¿Desea eliminar el registro?", MsgBoxStyle.YesNo, "Confirmar...")
        If resp = 6 Then
            Call SetSqlCitra("DELETE FROM LIQUIDACION WHERE IdLiquidacion=" & txtFolio.Text)
            Call SetSqlCitra("UPDATE KARDEX Set Inicial=" & txtInicial.Text & " WHERE IdBoleto=" & txtCidBoleto.Text)

            Es_Buscado = False
            txtFolio.Text = -1
            txtFolio.Text = 0

            Bitacora.RegistraActividad("Eliminó la liquidación del autobus " & txtAutobus.Text.Trim & " del dia " & datFecha.Text)
        Else
            Bitacora.RegistraActividad("Intentó eliminar la liquidación del autobus " & txtAutobus.Text.Trim & " del dia " & datFecha.Text)
        End If
    End Sub
    Private Sub ImprimirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim ID As Integer = BuscarIntDatoCitra("LIQUIDACION", "IDLIQUIDACION", "IDLIQUIDACION=" & txtFolio.Text)
        If ID > 0 Then
            'Imprimir
            If radioPreLiquidacion.Checked = True Then
                imprimirPapeletaBoletos(False)
            Else
                imprimirPapeletaCuota(False)
            End If
        Else
            MsgBox("No se puede imprimir una liquidación que no ha sido guardada", MsgBoxStyle.Exclamation, "Aviso")
        End If
    End Sub

    Private Sub ToolStripButton5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
     

    End Sub
    Sub GuardarPorCuota()
        If DiaTrabajado(datFecha.Value) = True Then
            MsgBox("El dia " & datFecha.Text & " ya ha sido archivado", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If txtAnalista.Text = "" Then
            MsgBox("Debes indicar el nombre del liquidador", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtAutobus.Text = "" Then
            MsgBox("Debes indicar el autobus", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtOperador.Text = "" Then
            MsgBox("Debes indicar el nombre del operador", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtVueltas.Text = 0 Then
            Dim resp As Integer = MsgBox("Una liquidacion con 0 vueltas no generará sueldo al operador, ¿Desea continuar?", MsgBoxStyle.YesNo)
            If resp <> 6 Then
                Exit Sub
            End If
        End If
        If txtVueltas.Text < 0 Then
            MsgBox("No se puede guardar las vueltas con valor negativo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtVueltas.Text > 25 Then
            Dim resp As Integer = MsgBox("¿Es correcta la cantidad de vueltas (" & txtVueltas.Text & ")", MsgBoxStyle.YesNo, "Aviso")
            If resp <> 6 Then
                Exit Sub
            End If
        End If
        If txtRuta.Text = "" Then
            MsgBox("Debes indicar la ruta", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Dim Codigo As String = BuscarStrDatoCitra("SELECT cCodigoV01 FROM RUTAS WHERE cCodigoV01='" & txtRuta.Text.Trim & "'")
        If Codigo.Trim = "" Then
            MsgBox("La ruta indicada no existe", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If


        Dim Liquidador As String = txtAnalista.Text
        Dim CodigoLiquidador As String = txtCodigoLiquidador.Text
        Dim Serie As String = txtSerie.Text.Trim
        Dim Fecha As Date = datFecha.Value

        Gatter()
        If liq.IdLiquidador = 0 Then
            MsgBox("El liquidador indicado no existe o esta inactivo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If liq.IdOperador = 0 Then
            MsgBox("El operador indicado no existe o esta inactivo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If liq.IdAutobus = 0 Then
            MsgBox("El autobus indicado no existe o esta inactivo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        liq.Guardar()

        'Imprimir
        If chImprimir.Checked = True Then
            imprimirPapeletaCuota(False)
        End If



        txtFolio.Text = -1
        txtFolio.Text = 0
        Application.DoEvents()

        Es_Buscado = False
        ToolStrip1.Enabled = True

        'Extra.FechaActididad = Now()

        Bitacora.RegistraActividad("Registró una liquidación del autobus " & txtAutobus.Text.Trim & " del dia " & datFecha.Text)

        Es_Buscado = False
        TotalLiquidacion()

        txtAnalista.Text = Liquidador
        txtCodigoLiquidador.Text = CodigoLiquidador
        txtSerie.Text = Serie
        datFecha.Text = Fecha
        radioLiquidacion.Checked = True


        Application.DoEvents()


        txtAutobus.Focus()
        txtAutobus.SelectAll()
        Application.DoEvents()
    End Sub
    Sub GuardarPorBoletaje()
        If DiaTrabajado(datFecha.Value) = True Then
            MsgBox("El dia " & datFecha.Text & " ya ha sido archivado", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If txtAnalista.Text = "" Then
            MsgBox("Debes indicar el nombre del liquidador", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtAutobus.Text = "" Then
            MsgBox("Debes indicar el autobus", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtOperador.Text = "" Then
            MsgBox("Debes indicar el nombre del operador", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtSerie.Text = "" Then
            MsgBox("Debes indicar la serie", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtTotalBoletos.Text < 1 Then
            MsgBox("No se puede guardar el total de boletos con valor 0 ó negativo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtPreferencial.Text < 0 Then
            MsgBox("No se pueden guardar el pagobus con valor negativo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtGeneral.Text < 0 Then
            MsgBox("No se pueden guardar el pagobus con valor negativo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtVueltas.Text = 0 Then
            Dim resp As Integer = MsgBox("Una liquidacion con 0 vueltas no generará sueldo al operador, ¿Desea continuar?", MsgBoxStyle.YesNo)
            If resp <> 6 Then
                Exit Sub
            End If
        End If
        If txtVueltas.Text < 0 Then
            MsgBox("No se puede guardar las vueltas con valor negativo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If
        If txtVueltas.Text > 25 Then
            Dim resp As Integer = MsgBox("¿Es correcta la cantidad de vueltas (" & txtVueltas.Text & ")", MsgBoxStyle.YesNo, "Aviso")
            If resp <> 6 Then
                Exit Sub
            End If
        End If
        If txtRuta.Text = "" Then
            MsgBox("Debes indicar la ruta", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Dim Codigo As String = BuscarStrDatoCitra("SELECT cCodigoV01 FROM RUTAS WHERE cCodigoV01='" & txtRuta.Text.Trim & "'")
        If Codigo.Trim = "" Then
            MsgBox("La ruta indicada no existe", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If


        Dim Liquidador As String = txtAnalista.Text
        Dim CodigoLiquidador As String = txtCodigoLiquidador.Text
        Dim Serie As String = txtSerie.Text.Trim
        Dim Fecha As Date = datFecha.Value

        Gatter()
        If liq.IdLiquidador = 0 Then
            MsgBox("El liquidador indicado no existe o esta inactivo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If liq.IdOperador = 0 Then
            MsgBox("El operador indicado no existe o esta inactivo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If liq.IdAutobus = 0 Then
            MsgBox("El autobus indicado no existe o esta inactivo", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        liq.Guardar()

        'Actualiza Numeraciones
        Call SetSqlCitra("UPDATE KARDEX SET Inicial=" & txtFinal.Text & " WHERE idBoleto=" & txtCidBoleto.Text)


        'Imprimir
        If chImprimir.Checked = True Then
            imprimirPapeletaBoletos(False)
        End If



        txtFolio.Text = -1
        txtFolio.Text = 0
        Application.DoEvents()

        Es_Buscado = False
        ToolStrip1.Enabled = True

        'Extra.FechaActididad = Now()

        Bitacora.RegistraActividad("Registró una liquidación del autobus " & txtAutobus.Text.Trim & " del dia " & datFecha.Text)

        Es_Buscado = False
        TotalLiquidacion()

        txtAnalista.Text = Liquidador
        txtCodigoLiquidador.Text = CodigoLiquidador
        txtSerie.Text = Serie
        datFecha.Text = Fecha
        radioPreLiquidacion.Checked = True


        Application.DoEvents()


        txtAutobus.Focus()
        txtAutobus.SelectAll()
        Application.DoEvents()

    End Sub

    Private Sub GuardarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If radioPreLiquidacion.Checked = True Then
            GuardarPorBoletaje()
        Else
            GuardarPorCuota()
        End If

    End Sub

    Private Sub ToolStripButton4_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Eliminar()

    End Sub

    Private Sub ToolStripButton2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
       
    End Sub

    Private Sub ToolStripButton3_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs)
       
    End Sub

    Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Close()

    End Sub

    Private Sub AlmacenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlmacenToolStripMenuItem.Click
        frmAlmacenBoletos.ShowDialog()

    End Sub

    Private Sub NumeracionesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumeracionesToolStripMenuItem.Click
        frmDotacion.ShowDialog()

    End Sub

    Private Sub txtRuta_KeyDown1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtRuta.KeyDown
        If e.KeyCode = Keys.F3 Then
            panelBuses.Visible = False
            panelNombres.Visible = False

            panelRutas.Visible = True
            txtBuscarRuta.Focus()
            txtBuscarRuta.Clear()
            txtBuscarRuta.SelectAll()
        End If
    End Sub

    Private Sub txtRuta_KeyPress1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtRuta.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            Dim Codigo As String = BuscarStrDatoCitra("SELECT CCodigoV01 FROM RUTAS WHERE CCodigoV01='" & txtRuta.Text.Trim & "'")

            If Codigo.Trim <> "" Then
                txtCodigoOperador.Focus()
                txtCodigoOperador.SelectAll()
            Else
                MsgBox("La ruta indicada no existe", MsgBoxStyle.Exclamation, "Aviso")
                txtRuta.Focus()
                txtRuta.SelectAll()
            End If

        End If
    End Sub

    Private Sub txtRuta_TextChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRuta.TextChanged

    End Sub
    Private Sub txtRuta_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)

    End Sub

    Private Sub txtRuta_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)

    End Sub

    Private Sub radioPreLiquidacion_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radioPreLiquidacion.CheckedChanged
        VerificaTipoLiquidacion()

    End Sub

    Private Sub txtTotal_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTotal.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            If radioPreLiquidacion.Checked = False Then
                GuardarPorCuota()
            Else
                GuardarPorBoletaje()
            End If
        End If
    End Sub

    Private Sub txtTotal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotal.TextChanged

    End Sub

    Private Sub CerrarDiaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)




    End Sub
    Sub CerrarDia()
        'Verifica que todas las rutas tengan asignado el concepto de Ventas
        Dim Rutas As Integer = BuscarIntDatoCitra("Select count(*) FROM Rutas")
        Dim RutasAsignadas As Integer = BuscarIntDatoCitra("Select count(*) from Conceptos where Tipo='Ventas'")
        Dim Faltan As Integer = Rutas - RutasAsignadas
        If Faltan > 0 Then
            MsgBox("No se puede cerrar el dia porque faltan " & Faltan & " rutas por asignar en Rutas > Conceptos", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        'Verifica que todas las rutas tengan asignado el cliente para envios
        Dim RutasConClientes As Integer = BuscarIntDatoCitra("Select count(*) from Rutas where Texto01<>''")
        Dim FaltanClientes As Integer = Rutas - RutasConClientes
        If FaltanClientes > 0 Then
            MsgBox("No se puede cerrar el dia poorque faltan " & FaltanClientes & " clientes para envio por asignar en el Catálogo de Rutas", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Dim cCodigoBol As String = ""
        Dim cCodigoASE As String = ""
        Dim RutaDLL As String = ""

        Try

            Dim key As Microsoft.Win32.RegistryKey
            key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(gsRegPath)
            RutaDLL = CType(key.GetValue("RutaDLL"), String)
            cCodigoBol = CType(key.GetValue("cCodigoBol"), String)
            cCodigoASE = CType(key.GetValue("cCodigoASE"), String)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
            MsgBox("Se interrumpio el proceso", MsgBoxStyle.Exclamation, "Aviso")
        End Try

        If Usa_AdminPAQ = True Then
            'ENTONCES SE USA EL SDK DE ADMINPAQ
            lblStatusDia.Text = "Cargando librerias..."
            Application.DoEvents()

            'Carga SDK
            Dim lError As Integer
            lblStatusDia.Text = "Cargando SDK de Adminpaq..."
            Application.DoEvents()

            Try
                Directory.SetCurrentDirectory(RutaDLL)
                lError = SDK_AdminPAQ.fInicializaSDK
                If lError <> 0 Then
                    MensajeError(lError)
                    End
                End If
            Catch ex As Exception
                lblStatus.Text = ex.Message
                MsgBox("No se pudo cargar el SDK de AdminPAQ", MsgBoxStyle.Exclamation, "Aviso")
                Exit Sub
            End Try

            'Abre Empresa de AdminPAQ
            lblStatusDia.Text = "Abriendo empresa de AdminPAQ..."
            Application.DoEvents()

            Try
                lError = SDK_AdminPAQ.fAbreEmpresa(Comercial)
                If lError <> 0 Then
                    MensajeError(lError)
                End If
            Catch ex As Exception
                MsgBox("No se pudo abrir la empresa de AdminPAQ", MsgBoxStyle.Exclamation, "Aviso")
                Exit Sub
            End Try

        Else
            'ENTONCES SE USA EL DE COMERCIAL
            'Carga Libreria
            lblStatusDia.Text = "Cargando SDK de ContPAQ I Comercial"
            Application.DoEvents()
            Dim lRet As Long
            lRet = fSDK_Inicializa(Comercial)
            If lRet <> 0 Then
                MsgBox("No pudo ser iniciado el SDK de Comercial", MsgBoxStyle.Exclamation, "Aviso")
                Exit Sub
            End If

        End If



        Dim Dias As Integer = DateDiff(DateInterval.Day, datDiaCerrar.Value, datFecha2.Value)

        If Dias < 0 Then
            MsgBox("El rango de fechas es incorrecto", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        ElseIf Dias = 0 Then
            If DiaTrabajado(datDiaCerrar.Value) = True Then
                MsgBox("El dia " & datDiaCerrar.Text & " ya ha sido archivado", MsgBoxStyle.Exclamation, "Aviso")
                Exit Sub
            End If
            'AQUI TAMBIEN
            Comienza(cCodigoBol, cCodigoASE)
        ElseIf Dias > 0 Then
            datDiaCerrar.Value = datDiaCerrar.Value.AddDays(-1)
            Application.DoEvents()
            For i = 0 To Dias
                datDiaCerrar.Value = datDiaCerrar.Value.AddDays(1)
                Application.DoEvents()
                If Not (DiaTrabajado(datDiaCerrar.Value) = True) Then
                    'AQUI SUCEDE TODO
                    Comienza(cCodigoBol, cCodigoASE)
                End If
            Next
        End If





        MsgBox("Los dias se han cerrado correctamente", MsgBoxStyle.Information, "Aviso")

        'Cierra el SDK
        'lblStatusDia.Text = "Cerrando SDK de AdminPAQ..."
        'Application.DoEvents()

        '     Try
        '   SDK_AdminPAQ.fCierraEmpresa()
        '  SDK_AdminPAQ.fTerminaSDK()
        '   Catch ex As Exception
        ' MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        ' MsgBox("No se pudo cerrar el SDK de AdminPAQ", MsgBoxStyle.Exclamation, "Aviso")
        '  End Try

        lblStatus.Text = ""
        Application.DoEvents()


    End Sub
    Sub Comienza(ByVal Producto As String, ByVal Almacen As String)

        'Genera Informacion para Envio
        Dim cnconn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Dim FechaLiquidacion As String = datDiaCerrar.Value.ToString("yyyy-dd-MM")
        Dim FechaLiquidacion2 As String = datDiaCerrar.Value.AddDays(1).ToString("yyyy-dd-MM")

        FechaLiquidacion = FechaLiquidacion & " 00:00:00"
        FechaLiquidacion2 = FechaLiquidacion2 & " 00:00:00"

        txtTotalLiquidaciones.Text = BuscarIntDatoCitra("SELECT COUNT(*) FROM Liquidacion WHERE Fecha='" & FechaLiquidacion & "'")

        Try
            lblStatusDia.Text = "Buscando liquidaciones..."
            Application.DoEvents()

            cnconn.ConnectionString = CitraConnection
            strSql = "Select IdRuta,SUM(Liquidacion) as Liquidacion FROM Liquidacion WHERE Fecha>='" & FechaLiquidacion & "' AND Fecha<='" & FechaLiquidacion2 & "' GROUP BY IdRuta"

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql

            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Dim CodigoCliente As String = 0
            Dim CodigoRuta As String = ""
            Dim CodigoConepto As String = ""
            Dim Fecha As Date = datDiaCerrar.Value
            Dim AdminPAQ As New clsAdminPAQ
            Dim Dia As New clsDiaTrabajo
            Dim Cont As Integer = 0
            Dim NombreRuta As String = ""

            Do While rdBuscar.Read()
                'Primero busca cliente para Envios

                Application.DoEvents()


                CodigoCliente = BuscarStrDatoCitra("Rutas", "Texto01", "IdRuta=" & rdBuscar("IdRuta"))
                CodigoRuta = BuscarStrDatoCitra("Rutas", "cCodigoV01", "IdRuta=" & rdBuscar("IdRuta"))
                lblStatusDia.Text = "Enviando registros a AdminPAQ de la ruta " & CodigoRuta
                'Busca Concepto
                CodigoConepto = BuscarStrDatoCitra("Conceptos", "CodigoConcepto", "CodigoRuta='" & CodigoRuta & "' AND Tipo='Ventas'")
                Fecha = datDiaCerrar.Value
                NombreRuta = BuscarStrDatoCitra("Rutas", "Nombre", "IdRuta=" & rdBuscar("IdRuta"))

                If Usa_AdminPAQ = True Then
                    AdminPAQ.EnviaAdminPAQ(Fecha, CodigoConepto, BuscarIntDatoComercial("SELECT CNOFOLIO FROM MGW10006 WHERE CCODIGOC01='" & CodigoConepto & "'") + 1, "LIQ", CodigoCliente, NombreRuta, "", Producto, Almacen, 1, rdBuscar("Liquidacion"))
                Else
                    admComercial.EnviaComercial(Fecha, CodigoConepto, BuscarIntDatoComercial("SELECT CNOFOLIO FROM MGW10006 WHERE CCODIGOC01='" & CodigoConepto & "'") + 1, "LIQ", CodigoCliente, NombreRuta, "", Producto, Almacen, 1, rdBuscar("Liquidacion"), AdminPAQ_Comercial.TIPO_DOCUMENTO_COMERCIAL.Ventas)
                End If


                Cont = Cont + 1
            Loop

            If Cont = 0 Then
                MsgBox("No se encontraron registros para procesar", MsgBoxStyle.Exclamation, "Aviso")
            Else
                Dia.Dia = Fecha.Day
                Dia.Mes = Fecha.Month
                Dia.Anio = Fecha.Year
                Dia.Insertar()
                'MsgBox("El dia se ha cerrado correctamente", MsgBoxStyle.Information, "Aviso")
                Bitacora.RegistraActividad("Cerró la Liquidacion del dia " & datFecha.Text)
            End If

        Catch ex As SqlException
            MessageBox.Show(ex.Message, "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)

        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try
    End Sub

    Private Sub ReAbrirDiaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub
    Sub ReAbrir()
        'Pide contraseña de reactivacion
        frmPassword.ShowDialog()
        If frmPassword.txtPass.Text.Trim <> "Ausl4321LIQUIDACION" Then
            MsgBox("La contraseña es incorrecta", MsgBoxStyle.Critical, "Aviso")
            Exit Sub
        End If

        'Carga Libreria
        '   lblStatusDia.Text = "Cargando librerias..."
        '  Application.DoEvents()

        '    Dim RutaDLL As String = ""
        'Dim cCodigoBol As String = ""
        'Dim cCodigoASE As String = ""

        'Try

        'Dim key As Microsoft.Win32.RegistryKey
        'key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(gsRegPath)
        'RutaDLL = CType(key.GetValue("RutaDLL"), String)
        'cCodigoBol = CType(key.GetValue("cCodigoBol"), String)
        'cCodigoASE = CType(key.GetValue("cCodigoASE"), String)
        'Catch ex As Exception
        'MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        'Exit Sub
        'MsgBox("Se interrumpio el proceso", MsgBoxStyle.Exclamation, "Aviso")
        'End Try

        'Carga SDK
        'Dim lError As Integer
        'lblStatusDia.Text = "Cargando SDK de Adminpaq..."
        'Application.DoEvents()

        '  Try
        'Directory.SetCurrentDirectory(RutaDLL)
        'lError = SDK_AdminPAQ.fInicializaSDK
        'If lError <> 0 Then
        ' MensajeError(lError)
        'End
        'End If
        'Catch ex As Exception
        ' MsgBox("No se pudo cargar el SDK de AdminPAQ", MsgBoxStyle.Exclamation, "Aviso")
        ' Exit Sub
        ' End Try

        'Abre Empresa de AdminPAQ
        'lblStatusDia.Text = "Abriendo empresa de AdminPAQ..."
        'Application.DoEvents()

        'Try
        ' lError = SDK_AdminPAQ.fAbreEmpresa(Comercial)
        ' If lError <> 0 Then
        ' MensajeError(lError)
        ' End If
        ' Catch ex As Exception
        ' MsgBox("No se pudo abrir la empresa de AdminPAQ", MsgBoxStyle.Exclamation, "Aviso")
        ' Exit Sub
        ' End Try

        'If Usa_AdminPAQ = True Then
        'Continuar = False
        'ImportaTablas(1)
        'Timer1.Enabled = True
        'Application.DoEvents()


        'Do While Continuar = False
        'lblStatusDia.Text = "Espere mientras se actualizan las tablas..."
        'Application.DoEvents()
        'Loop
        'End If


        Dim Dias As Integer = DateDiff(DateInterval.Day, datDiaCerrar.Value, datFecha2.Value)

        If Dias < 0 Then
            MsgBox("El rango de fechas es incorrecto", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        ElseIf Dias = 0 Then
            If DiaTrabajado(datDiaCerrar.Value) = False Then
                MsgBox("El dia no se ha cerrado", MsgBoxStyle.Exclamation, "Aviso")
                Exit Sub
            End If
            'AQUI(TAMBIEN)
            Comenzar2()
        ElseIf Dias > 0 Then
            datDiaCerrar.Value = datDiaCerrar.Value.AddDays(-1)
            Application.DoEvents()
            For i = 0 To Dias
                datDiaCerrar.Value = datDiaCerrar.Value.AddDays(1)
                Application.DoEvents()
                If Not (DiaTrabajado(datDiaCerrar.Value) = True) Then
                    'AQUI SUCEDE TODO
                    Comenzar2()
                End If
            Next
        End If
        MsgBox("El dia se ha reactivado", MsgBoxStyle.Information, "Aviso")
        Bitacora.RegistraActividad("Re-abrió la Liquidacion del dia " & datFecha.Text)

        'Cierra el SDK
        'lblStatusDia.Text = "Cerrando SDK de AdminPAQ..."
        'Application.DoEvents()

        'Try
        'SDK_AdminPAQ.fCierraEmpresa()
        'SDK_AdminPAQ.fTerminaSDK()
        'Catch ex As Exception
        'MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        'MsgBox("No se pudo cerrar el SDK de AdminPAQ", MsgBoxStyle.Exclamation, "Aviso")
        'End Try

        '        lblStatus.Text = ""
        '       Application.DoEvents()

    End Sub
    Sub Comenzar2()
        'Primero trae los codigos de Ruta
        'Variables para busqueda de rutas
        '   Dim cnConnCitra As New SqlConnection
        '  Dim strSqlCitra As String = ""
        '  Dim cmdBuscarCitra As New SqlCommand
        '  Dim rdBuscarCitra As SqlDataReader
        '  Dim Concepto As String = ""
        '  Dim CadenaConceptos As String = ""
        '  Dim cIDConce01 As Integer = 0

        'variables para busqueda en AdminPAQ


        'Arma conceptos
        'Try
        'lblStatusDia.Text = "Buscando conceptos..."
        'Application.DoEvents()

        'cnConnCitra.ConnectionString = CitraConnection
        'strSqlCitra = "Select CodigoConcepto FROM Conceptos Where Tipo='Ventas' GROUP BY CodigoConcepto"
        'cmdBuscarCitra.Connection = cnConnCitra
        'cmdBuscarCitra.CommandText = strSqlCitra
        'cnConnCitra.Open()
        'rdBuscarCitra = cmdBuscarCitra.ExecuteReader

        '        Do While rdBuscarCitra.Read()
        'Por Cada Ruta Buscar Registros en conceptos
        'Concepto = rdBuscarCitra("CodigoConcepto")
        'If Usa_AdminPAQ = True Then
        ' cIDConce01 = BuscarStrDatoCitra("MGW10006", "cidConce01", "cCodigoC01='" & Concepto & "'")
        ' Else
        ' cIDConce01 = BuscarStrDatoComercial("SELECT CIDCONCEPTODOCUMENTO WHERE CCODIGOCONCEPTO='" & Concepto & "'")
        ' End If

        'CadenaConceptos = CadenaConceptos & "," & cIDConce01
        'Loop
        'CadenaConceptos = Mid(CadenaConceptos, 2)
        'Catch ex As Exception
        ' MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        ' Finally
        ' If cnConnCitra.State = ConnectionState.Open Then
        ' cnConnCitra.Close()
        ' End If
        ' End Try

        'Dim FechaLiquidacion As String = datDiaCerrar.Value.ToString("MM/dd/yyyy")
        Dim Fecha As Date = datDiaCerrar.Value
        Dim DT As New clsDiaTrabajo
        'Dim cnconnAdmin As New SqlConnection
        'Dim strSqlAdmin As String = ""
        'Dim cmdBuscarAdmin As New SqlCommand
        'Dim rdBuscarAdmin As SqlDataReader
        'Dim cidDocum01 As Integer = 0

        'Try


        'If Usa_AdminPAQ = True Then
        'lblStatusDia.Text = "Buscando registros en AdminPAQ..."
        'Application.DoEvents()
        'cnconnAdmin.ConnectionString = CitraConnection
        'strSqlAdmin = "SELECT cIdDocum01 FROM MGW10008 WHERE CIDCONCE01 IN(" & CadenaConceptos & ") AND CONVERT(VARCHAR,CFECHA,101)='" & FechaLiquidacion & "'"

        '        Else
        '        lblStatusDia.Text = "Buscando registros en ContPAQ I Comercial..."
        '        Application.DoEvents()
        '        cnconnAdmin.ConnectionString = CitraConnection
        '        strSqlAdmin = "SELECT cIdDocum FROM admDOCUMENTOS WHERE CIDCONCEPTODOCUMENTO IN(" & CadenaConceptos & ") AND CONVERT(VARCHAR,CFECHA,101)='" & FechaLiquidacion & "'"
        '        End If
        '        cmdBuscarAdmin.Connection = cnconnAdmin
        '        cmdBuscarAdmin.CommandText = strSqlAdmin
        '       cnconnAdmin.Open()


        '        rdBuscarAdmin = cmdBuscarAdmin.ExecuteReader
        '        Dim Cont As Integer = 0
        '        Do While rdBuscarAdmin.Read()
        ' Cont = Cont + 1
        ' lblStatusDia.Text = "Borrando " & Cont & " Registros..."
        ' Application.DoEvents()

        ' cidDocum01 = rdBuscarAdmin("cidDocum01")
        ' BorraDocumento(cidDocum01)
        ' Loop

        'Catch ex As SqlException
        ' MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        ' Finally
        'If cnconnAdmin.State = ConnectionState.Open Then
        ' cnconnAdmin.Close()
        ' End If
        'End Try

        DT.Dia = Fecha.Day
        DT.Mes = Fecha.Month
        DT.Anio = Fecha.Year
        DT.Borrar()





    End Sub
    Function BorraDocumento(ByVal IDDocto As Integer)
        Dim lRet As Long

        lRet = SDK_AdminPAQ.fBuscarIdDocumento(IDDocto)
        If lRet <> 0 Then
            MensajeError(lRet)
            Return 0
        Else
            SDK_AdminPAQ.fBorraDocumento()
            Return 1
        End If
    End Function

    Private Sub LiquidaciónToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LiquidaciónToolStripMenuItem.Click
        frmRLiquidacion.ShowDialog()
    End Sub

    Private Sub IngresosToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub DetalladoDeIngresosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DetalladoDeIngresosToolStripMenuItem.Click
        frmRIngresosDetallado.ShowDialog()
    End Sub

    Private Sub ActualizarOperadoresToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        frmImportarOperadores.ShowDialog()
    End Sub

    Private Sub txtBuscaLiquidador_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtBuscaLiquidador.KeyPress
        If radioPreLiquidacion.Checked = True Then
            If e.KeyChar = Chr(Keys.Enter) Then
                PanelLiquidadores.Visible = False
                Dim Nombre As String = dgLiquidadores.CurrentRow.Cells(1).Value.ToString.Trim
                Dim Codigo As String = dgLiquidadores.CurrentRow.Cells(0).Value.ToString.Trim
                txtCodigoLiquidador.Text = Codigo
                txtAnalista.Text = Nombre
                txtFinal.Focus()
                txtFinal.SelectAll()

            ElseIf e.KeyChar = Chr(Keys.Escape) Then
                PanelLiquidadores.Visible = False
            End If
        Else
            If e.KeyChar = Chr(Keys.Enter) Then
                PanelLiquidadores.Visible = False
                Dim Nombre As String = dgLiquidadores.CurrentRow.Cells(1).Value.ToString.Trim
                Dim Codigo As String = dgLiquidadores.CurrentRow.Cells(0).Value.ToString.Trim
                txtCodigoLiquidador.Text = Codigo
                txtAnalista.Text = Nombre
                txtVueltas.Focus()
                txtVueltas.SelectAll()

            ElseIf e.KeyChar = Chr(Keys.Escape) Then
                PanelLiquidadores.Visible = False
            End If
        End If
    End Sub

    Private Sub txtBuscaLiquidador_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscaLiquidador.TextChanged
        CargaLiquidadores()

    End Sub


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        milisegundo += 1
        If milisegundo = 9 Then
            milisegundo = 0
            segundo += 1

            If segundo = 5 Then
                Application.DoEvents()
                If BuscarIntDatoCitra("SELECT Resultado FROM EstadoImportacion WHERE IdImportacion=1") = 0 Then
                    Continuar = True
                    Timer1.Enabled = False
                    Application.DoEvents()
                Else
                    segundo = 1
                End If
            End If
        End If

    End Sub

    Private Sub dgLiquidadores_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgLiquidadores.CellDoubleClick
        If radioPreLiquidacion.Checked = True Then

            PanelLiquidadores.Visible = False
            Dim Nombre As String = dgLiquidadores.CurrentRow.Cells(1).Value.ToString.Trim
            Dim Codigo As String = dgLiquidadores.CurrentRow.Cells(0).Value.ToString.Trim
            txtCodigoLiquidador.Text = Codigo
            txtAnalista.Text = Nombre
            txtFinal.Focus()
            txtFinal.SelectAll()
        Else
            PanelLiquidadores.Visible = False
            Dim Nombre As String = dgLiquidadores.CurrentRow.Cells(1).Value.ToString.Trim
            Dim Codigo As String = dgLiquidadores.CurrentRow.Cells(0).Value.ToString.Trim
            txtCodigoLiquidador.Text = Codigo
            txtAnalista.Text = Nombre
            txtVueltas.Focus()
            txtVueltas.SelectAll()
        End If
    End Sub

    Private Sub chScanner_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chScanner.CheckedChanged
        If chScanner.Checked = True Then
            'lstUbicación.Enabled = True
            txtIPScanner.Enabled = True
            btnIPScanner.Enabled = True
            btnConectar.Enabled = True
            txtConexion.Enabled = True
            txtCodigoOperador.Enabled = False
        Else
            'lstUbicación.Enabled = False
            txtIPScanner.Enabled = False
            btnIPScanner.Enabled = False
            btnConectar.Enabled = False
            txtConexion.Enabled = False
            txtCodigoOperador.Enabled = True

        End If
    End Sub

    Private Sub lstUbicación_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstUbicación.SelectedIndexChanged
        txtIPScanner.Text = BuscarStrDatoCitra("SELECT IP FROM IPScanner WHERE UBICACION='" & lstUbicación.Text & "'")
    End Sub

    Private Sub btnIPScanner_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIPScanner.Click
        Dim IP As New clsIPScanner
        IP.IP = txtIPScanner.Text
        IP.Ubicacion = lstUbicación.Text
        Dim IdIP As Integer = BuscarIntDatoCitra("SELECT Id FROM IPScanner WHERE UBICACION='" & lstUbicación.Text & "'")
        If IdIP > 0 Then
            IP.Actualizar()
        Else
            IP.Insertar()
        End If

        MsgBox("La ip del Scanner se ha cambiado exitosamente", MsgBoxStyle.Information, "Aviso")
    End Sub

    Private Sub btnConectar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConectar.Click
        FalloalAbrir = False
        'ABRE DISPOSITIVO DE LECTURA DE TARJETAS
        IniciaLector()
        If FalloalAbrir = True Then
            txtConexion.AppendText("Debe verificar la conexión del lector de tarjetas" & vbNewLine)
            chScanner.Checked = False
        Else
            chScanner.Checked = True
        End If
    End Sub

    Private Sub ToolStripButton6_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton6.Click
        TabPage1.Parent = TabControl1
        TabPage2.Parent = Nothing
        TabPage4.Parent = Nothing
        TabControl1.SelectedTab = TabPage1
    End Sub

    Private Sub ToolStripButton7_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton7.Click
        TabPage1.Parent = Nothing
        TabPage2.Parent = TabControl1
        TabPage4.Parent = Nothing
        TabControl1.SelectedTab = TabPage2
    End Sub

    Private Sub ToolStripButton8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ToolStripButton9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton9.Click
        TabPage1.Parent = Nothing
        TabPage2.Parent = Nothing
        TabPage4.Parent = TabControl1
        TabControl1.SelectedTab = TabPage4

        datDiaCerrar.Value = datFecha.Value


        If DiaTrabajado(datDiaCerrar.Value) = True Then
            btnCerrar.Enabled = False
            btnAbrir.Enabled = True
        Else
            btnCerrar.Enabled = True
            btnAbrir.Enabled = False
        End If

        lblStatusDia.Text = ""
        lblStatusImportacion.Text = ""

        lblUltima.Text = BuscarStrDatoCitra("SELECT UltimaActualizacion FROM OperadoresGlobalActualizacion WHERE ID=1")
    End Sub

    Private Sub ToolStripButton5_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton5.Click

        If radioPreLiquidacion.Checked = True Then
            GuardarPorBoletaje()
        Else
            GuardarPorCuota()
        End If


    End Sub

    Private Sub ToolStripButton3_Click_3(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
        If Len(txtAutobus.Text) = 0 Then
            MsgBox("Debes indicar un autobus a buscar", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Dim strResult As String
        Dim fBusqueda As New frmBuscarLiquidaciones

        fBusqueda.ShowDialog()

        If fBusqueda.DialogResult = Windows.Forms.DialogResult.OK Then
            strResult = fBusqueda.Valor

            If strResult <> "" Then
                txtFolio.Text = strResult
                Es_Buscado = True
                'Actualizar()
            End If
        End If
    End Sub

    Private Sub ToolStripButton2_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        Dim ID As Integer = BuscarIntDatoCitra("LIQUIDACION", "IDLIQUIDACION", "IDLIQUIDACION=" & txtFolio.Text)
        If ID > 0 Then
            'Imprimir
            If radioPreLiquidacion.Checked = True Then
                imprimirPapeletaBoletos(False)
            Else
                imprimirPapeletaCuota(False)
            End If
        Else
            MsgBox("No se puede imprimir una liquidación que no ha sido guardada", MsgBoxStyle.Exclamation, "Aviso")
        End If
    End Sub

    Private Sub ToolStripButton4_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton4.Click
        Eliminar()

    End Sub

    Private Sub ToolStripButton1_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Close()

    End Sub

    Private Sub ToolStripButton1_Click_3(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Close()

    End Sub

    Private Sub datDiaCerrar_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles datDiaCerrar.ValueChanged
        If DiaTrabajado(datDiaCerrar.Value) = True Then
            btnCerrar.Enabled = False
            btnAbrir.Enabled = True
        Else
            btnCerrar.Enabled = True
            btnAbrir.Enabled = False
        End If
    End Sub

    Private Sub btnCerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCerrar.Click


        CerrarDia()




    End Sub

    Private Sub btnAbrir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAbrir.Click
        ReAbrir()
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        If CITRA = "ctCITRAAUSL2012" Then
            Dim BD_ACG As String = "ctNOM2014ACG"
            Dim BD_AUSL As String = "ctNOM2014AUSL"
            Dim BD_ASP As String = "ctNOM2011ASP"
            Dim BD_LCB As String = "ctNOM2013LCB"

            Registros = 0

            'ConnectionACG = "Server=192.168.254.246;Database=" & BD_ACG & "; user id = SA; password = Ausl4321OPTRA;"
            ConnectionACG = "data source = 192.168.254.246\COMPAC; initial catalog =" & BD_ACG & "; user id = sa; password = Ausl4321OPTRA "
            ConnectionAUSL = "data source = 192.168.254.246\COMPAC; initial catalog =" & BD_AUSL & "; user id = sa; password = Ausl4321OPTRA "
            ConnectionASP = "data source = 192.168.254.246\COMPAC; initial catalog =" & BD_ASP & "; user id = sa; password = Ausl4321OPTRA "
            ConnectionLCB = "data source = 192.168.254.246\COMPAC; initial catalog =" & BD_LCB & "; user id = sa; password = Ausl4321OPTRA "

            CargaACG()
            CargaAUSL()
            CargaASP()
            CargaLCB()

            Call SetSqlCitra("UPDATE OperadoresGlobalActualizacion SET UltimaActualizacion='" & Now.ToString("MM/dd/yyyy") & "' WHERE ID=1")
            lblUltima.Text = BuscarStrDatoCitra("SELECT UltimaActualizacion FROM OperadoresGlobalActualizacion WHERE ID=1")
        Else
            CargaEmpleadosNominas()

            Call SetSqlCitra("UPDATE OperadoresGlobalActualizacion SET UltimaActualizacion='" & Now.ToString("MM/dd/yyyy") & "' WHERE ID=1")
            lblUltima.Text = BuscarStrDatoCitra("SELECT UltimaActualizacion FROM OperadoresGlobalActualizacion WHERE ID=1")
        End If

        lblStatusImportacion.Text = "Listo"
    End Sub
    Sub CargaEmpleadosNominas()
        Dim cnConn As New SqlConnection
        cnConn.ConnectionString = NominasConnection

        Dim cmdBuscar As New SqlCommand
        cmdBuscar.Connection = cnConn
        cmdBuscar.CommandText = "SELECT * From NOM10001 " 'WHERE IdPuesto=8 "

        Dim rdBuscar As SqlDataReader

        cnConn.Open()
        rdBuscar = cmdBuscar.ExecuteReader

        Dim IdOperador As Integer = 0

        Do While rdBuscar.Read()
            Operador.IDEmpleado = rdBuscar("IdEmpleado")
            Operador.Codigo = rdBuscar("CodigoEmpleado").ToString.Trim
            Operador.Nombre = rdBuscar("NombreLargo").ToString.Trim
            Operador.EstadoEmpleado = rdBuscar("EstadoEmpleado").ToString.Trim
            Operador.Empresa = "---"
            IdOperador = BuscarIntDatoCitra("OperadoresGlobal", "IdOperador", "Codigo='" & Operador.Codigo & "' AND Empresa='" & Operador.Empresa & "'")
            If IdOperador > 0 Then
                Operador.IdOperador = IdOperador
                Operador.Actualizar()
            Else
                Operador.Insertar()
            End If
            Actual = Actual + 1
            lblStatusImportacion.Text = "Importando " & Actual & " registros"
            Application.DoEvents()
        Loop
    End Sub
    Sub CargaACG()
        Dim cnConn As New SqlConnection
        cnConn.ConnectionString = ConnectionACG

        Dim cmdBuscar As New SqlCommand
        cmdBuscar.Connection = cnConn
        cmdBuscar.CommandText = "SELECT * From NOM10001 WHERE IdPuesto=8 "

        Dim rdBuscar As SqlDataReader

        cnConn.Open()
        rdBuscar = cmdBuscar.ExecuteReader

        Dim IdOperador As Integer = 0

        Do While rdBuscar.Read()
            Operador.IDEmpleado = rdBuscar("IdEmpleado")
            Operador.Codigo = rdBuscar("CodigoEmpleado").ToString.Trim
            Operador.Nombre = rdBuscar("NombreLargo").ToString.Trim
            Operador.EstadoEmpleado = rdBuscar("EstadoEmpleado").ToString.Trim
            Operador.Empresa = "ACG"
            IdOperador = BuscarIntDatoCitra("OperadoresGlobal", "IdOperador", "Codigo='" & Operador.Codigo & "' AND Empresa='" & Operador.Empresa & "'")
            If IdOperador > 0 Then
                Operador.IdOperador = IdOperador
                Operador.Actualizar()
            Else
                Operador.Insertar()
            End If
            Actual = Actual + 1
            lblStatusImportacion.Text = "Importando " & Actual & " registros"
            Application.DoEvents()
        Loop
    End Sub
    Sub CargaAUSL()
        Dim cnConn As New SqlConnection
        cnConn.ConnectionString = ConnectionAUSL

        Dim cmdBuscar As New SqlCommand
        cmdBuscar.Connection = cnConn
        cmdBuscar.CommandText = "SELECT * From NOM10001 WHERE IdPuesto=60 "


        Dim rdBuscar As SqlDataReader

        cnConn.Open()
        rdBuscar = cmdBuscar.ExecuteReader

        Dim IdOperador As Integer = 0

        Do While rdBuscar.Read()
            Operador.IDEmpleado = rdBuscar("IdEmpleado")
            Operador.Codigo = rdBuscar("CodigoEmpleado").ToString.Trim
            Operador.Nombre = rdBuscar("NombreLargo").ToString.Trim
            Operador.EstadoEmpleado = rdBuscar("EstadoEmpleado").ToString.Trim
            Operador.Empresa = "AUSL"
            IdOperador = BuscarIntDatoCitra("OperadoresGlobal", "IdOperador", "Codigo='" & Operador.Codigo & "' AND Empresa='" & Operador.Empresa & "'")
            If IdOperador > 0 Then
                Operador.IdOperador = IdOperador
                Operador.Actualizar()
            Else
                Operador.Insertar()
            End If
            Actual = Actual + 1
            lblStatusImportacion.Text = "Importando " & Actual & " registros"
            Application.DoEvents()
        Loop
    End Sub
    Sub CargaASP()
        Dim cnConn As New SqlConnection
        cnConn.ConnectionString = ConnectionASP

        Dim cmdBuscar As New SqlCommand
        cmdBuscar.Connection = cnConn
        cmdBuscar.CommandText = "SELECT * From NOM10001 WHERE IdPuesto=2 "

        Dim rdBuscar As SqlDataReader

        cnConn.Open()
        rdBuscar = cmdBuscar.ExecuteReader

        Dim IdOperador As Integer = 0

        Do While rdBuscar.Read()
            Operador.IDEmpleado = rdBuscar("IdEmpleado")
            Operador.Codigo = rdBuscar("CodigoEmpleado").ToString.Trim
            Operador.Nombre = rdBuscar("NombreLargo").ToString.Trim
            Operador.EstadoEmpleado = rdBuscar("EstadoEmpleado").ToString.Trim
            Operador.Empresa = "ASP"
            IdOperador = BuscarIntDatoCitra("OperadoresGlobal", "IdOperador", "Codigo='" & Operador.Codigo & "' AND Empresa='" & Operador.Empresa & "'")
            If IdOperador > 0 Then
                Operador.IdOperador = IdOperador
                Operador.Actualizar()
            Else
                Operador.Insertar()
            End If
            Actual = Actual + 1
            lblStatusImportacion.Text = "Importando " & Actual & " registros"
            Application.DoEvents()
        Loop
    End Sub
    Sub CargaLCB()
        Dim cnConn As New SqlConnection
        cnConn.ConnectionString = ConnectionLCB

        Dim cmdBuscar As New SqlCommand

        cmdBuscar.Connection = cnConn
        cmdBuscar.CommandText = "SELECT * From NOM10001 WHERE IdPuesto=98 "

        Dim rdBuscar As SqlDataReader

        cnConn.Open()
        rdBuscar = cmdBuscar.ExecuteReader

        Dim IdOperador As Integer = 0

        Do While rdBuscar.Read()
            Operador.IDEmpleado = rdBuscar("IdEmpleado")
            Operador.Codigo = rdBuscar("CodigoEmpleado").ToString.Trim
            Operador.Nombre = rdBuscar("NombreLargo").ToString.Trim
            Operador.EstadoEmpleado = rdBuscar("EstadoEmpleado").ToString.Trim
            Operador.Empresa = "LCB"
            IdOperador = BuscarIntDatoCitra("OperadoresGlobal", "IdOperador", "Codigo='" & Operador.Codigo & "' AND Empresa='" & Operador.Empresa & "'")
            If IdOperador > 0 Then
                Operador.IdOperador = IdOperador
                Operador.Actualizar()
            Else
                Operador.Insertar()
            End If
            Actual = Actual + 1
            lblStatusImportacion.Text = "Importando " & Actual & " registros"
            Application.DoEvents()
        Loop
    End Sub

    Private Sub txtCodigoLiquidador_KeyDown1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCodigoLiquidador.KeyDown
        If e.KeyCode = Keys.F3 Then
            panelRutas.Visible = False
            panelBuses.Visible = False
            panelNombres.BringToFront()
            panelNombres.Visible = True
            OrigenNombre = "L"
            txtBuscarNombre.Focus()
            txtBuscarNombre.Clear()
            txtBuscarNombre.SelectAll()
        End If
    End Sub
    Private Sub txtCodigoLiquidador_KeyPress1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCodigoLiquidador.KeyPress
        If Asc(e.KeyChar) = 13 Or Asc(e.KeyChar) = 9 Then
            Dim Nombre As String = BuscarStrDatoInicial("Liquidadores", "NombreCompleto", "Codigo='" & txtCodigoLiquidador.Text.Trim & "' AND EstadoEmpleado<>'B'")
            If Nombre <> "" Then
                txtAnalista.Text = Nombre.Trim
                txtAutobus.Focus()
                txtAutobus.SelectAll()
                Application.DoEvents()
            Else
                MsgBox("El codigo del Liquidador indicado, no existe o se encuentra inactivo", MsgBoxStyle.Exclamation, "Aviso")
                txtAnalista.Clear()
                txtCodigoLiquidador.SelectAll()
            End If
        End If
    End Sub
    Private Sub btnBuscarLiquidador_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscarLiquidador.Click
        panelRutas.Visible = False
        panelBuses.Visible = False
        PanelLiquidadores.Visible = True

        PanelLiquidadores.BringToFront()
        panelNombres.Visible = False
        OrigenNombre = "L"
        txtBuscarNombre.Focus()
        txtBuscarNombre.Clear()
        txtBuscarNombre.SelectAll()
    End Sub
    Private Sub btnLiquidado_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLiquidado.Click
        'BUSCAR TARJETA
        Dim CardID As Integer
        Dim CustomID As Integer

        result = BS_ReadCardIDEx(handle_Renamed, CardID, CustomID)
        lblStatusLiquidacion.Text = "Leyendo tarjeta..."
        Application.DoEvents()
        'tbxMessage.AppendText("Leyendo tarjeta..." & vbNewLine)
        If result <> 0 Then
            lblStatusLiquidacion.Text = "El tiempo de espera expiró. Error : " & result
            Application.DoEvents()
            'tbxMessage.AppendText("El tiempo de espera expiró. Error : " & result & vbNewLine)
            Exit Sub
        End If


        Dim CodigoTarjeta As String = CardID

        Dim CodigoOperador As String = BuscarStrDatoCitra("SELECT Codigo FROM Tarjetas WHERE CodigoTarjeta='" & CodigoTarjeta & "'")
        Dim IdOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM Tarjetas WHERE CodigoTarjeta='" & CodigoTarjeta & "'")
        If IdOperador > 0 Then
            lblStatusLiquidacion.Text = "Se identifico correctamente"
            Application.DoEvents()
            'tbxMessage.AppendText("Se identifico correctamente" & vbNewLine)
        Else
            lblStatusLiquidacion.Text = "La tarjeta " & CodigoTarjeta & " se identifico, pero no ha sido asignada"
            Application.DoEvents()
            'tbxMessage.AppendText("La tarjeta identifico, pero no ha sido asignada" & vbNewLine)
            Exit Sub
        End If

        Dim FechaActual As Date = Now()
        Dim Vencimiento As Date = BuscarDateDatoCitra("SELECT TerminoVigencia FROM Tarjetas WHERE CodigoTarjeta='" & CodigoTarjeta & "'")

        If Vencimiento < FechaActual Then
            lblStatusLiquidacion.Text = "La tarjeta ya esta vencida..."
            Application.DoEvents()
            Exit Sub
        End If

        Dim EstadoEmpleado As String = BuscarStrDatoCitra("SELECT EstadoEmpleado FROM OperadoresGlobal WHERE IdOperador=" & IdOperador)
        If EstadoEmpleado = "B" Then
            lblStatusLiquidacion.Text = "El operador es Baja..."
            Application.DoEvents()
            Exit Sub
        End If

        'Dim CodigoOperador As String = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE IdOperador=" & IdOperador)
        'txtOperador.Text = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE IdOperador=" & IdOperador)
        'txtCodigoOperador.Text = BuscarStrDatoCitra("SELECT Codigo FROM OperadoresGlobal WHERE IdOperador=" & IdOperador)
        'Application.DoEvents()
        If txtCodigoOperador.Text = CodigoOperador Then
            btnLiquidado.Enabled = False
            btnNoLiquidado.Enabled = False
            liq.Importe03 = 1
            liq.Texto02 = "1"
            ToolStripButton5.Enabled = False
            liq.IdLiquidacion = txtFolio.Text
            liq.ActualizarParaVisor()
        Else
            lblStatusLiquidacion.Text = "La tarjeta no corresponde a la liquidación seleccionada "
        End If




    End Sub
    Private Sub btnNoLiquidado_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNoLiquidado.Click
        btnLiquidado.Enabled = True
        btnNoLiquidado.Enabled = False

        liq.Texto02 = "0"
        liq.IdLiquidacion = txtFolio.Text
        liq.ActualizarParaVisor()
    End Sub


    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = True Then
            txtIPScanner.Enabled = True
            btnIPScanner.Enabled = True
            btnConectar.Enabled = True
            txtConexion.Enabled = True
        End If
    End Sub
End Class